如何在Recoil Atom中写入(=更新)Localstorage对象



我尝试在代码下面获取更新Recoil原子对象值的LocalStorge值。

const LoginState = atom({
key: 'login',
default : null
});

const Home: NextPage = () => {
const [login, setLogin] = useRecoilState(LoginState)
useEffect(()=>{
let localData = localStorage.getItem("token")
if(login === null || undefined){
if(localData !== null || undefined){
setLogin(localData)
}else{
setLogin(null)
}
}
}, [login])

但它有这样的错误

Argument of type 'string | null' is not assignable to parameter of type '((currVal: null) => null) | null'.
Type 'string' is not assignable to type '((currVal: null) => null) | null'**.ts(2345)**
<br>

我认为这个问题是打字造成的。据我所知,localStorage对象的类型是字符串或null我该如何解决它?

我在写问题时找到了解决方案
原子对象需要键入
首先,定义在原子中使用的类型

const LoginState = atom<loginState>({
key: 'login',
default : {
localValue : null
}
});

其次,添加定义到原子对象的类型,如

useEffect(()=>{
let localData = localStorage.getItem("token")
if(login === null || undefined){
if(localData !== null || undefined){
setLogin({localValue : localData})
}else{
setLogin({localValue : null})
}
}
}, [login])

最后,你可以根据你的类型进行修复

PD_6

最新更新