简体   繁体   English

State 未在 useEffect 中设置

[英]State not set in useEffect

I have a function to get data from local storage and set that local storage value to state but value doesn't set the state我有一个 function 从本地存储获取数据并将本地存储值设置为 state 但值没有设置 state

this is my code,这是我的代码,

 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)
        }
    }

I'm calling this function in useEffect, Can anyone tell what I am doing wrong and please help me to solve this我在useEffect中调用这个function,谁能告诉我做错了什么,请帮我解决这个问题

setMobilenum is the asynchronous method, so you can't get the updated value of mobileNum right after setMobilenum . setMobilenum是异步方法,因此您无法在setMobilenum之后立即获取mobileNum的更新值。 You should get it in the another useEffect with adding a dependency 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