[英]State not set in useEffect
我有一个 function 从本地存储获取数据并将本地存储值设置为 state 但值没有设置 state
这是我的代码,
const [mobileNum, setMobilenum] = useState();
useEffect(() => {
getDatalocal();
}, []);
async function getDatalocal() { // get data from local
try {
let mobileNumRes = await AsyncStorage.getItem('@number_Token')
setMobilenum(mobileNumRes) // set mobile number for state
console.log("mobile num ======================================>>>", mobileNum)
} catch (error) {
console.log("error in get mobile no", error)
}
}
我在useEffect中调用这个function,谁能告诉我做错了什么,请帮我解决这个问题
setMobilenum
是异步方法,因此您无法在setMobilenum
之后立即获取mobileNum
的更新值。 您应该通过添加依赖mobileNum
在另一个 useEffect 中获得它。
const [mobileNum, setMobilenum] = useState();
useEffect(() => {
getDatalocal();
}, []);
async function getDatalocal() { // get data from local
try {
let mobileNumRes = await AsyncStorage.getItem('@number_Token')
setMobilenum(mobileNumRes)
} catch (error) {
console.log("error in get mobile no", error)
}
}
useEffect(() => {
console.log("mobile num ==============>>>", mobileNum)
}, [mobileNum]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.