繁体   English   中英

State 未在 useEffect 中设置

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM