【问题标题】:react native set function not updating variables反应本机设置功能不更新变量
【发布时间】:2021-08-18 03:39:53
【问题描述】:

我有以下代码

    const fetchCurrentUser = async () => {
        let u = await firebase.auth().currentUser;
        setUser(u)
        console.log(user)
        let prof = await firebase.firestore().collection('abc').doc(u.uid).get();
        prof === null ? prof = await firebase.firestore().collection('efg').doc(u.uid).get() : null;
        setUserProfile(prof);
        console.log(u)
        console.log(prof)
        console.log(user)
        console.log(userProfile)
    }

    useEffect(() => {
        fetchCurrentUser();
    }, [])

代码的输出是

someObject()
someObject()
null
null

当 u 和 prof 不为 null 并且就在我设置 user = u 和 profile = prof 的上方时,用户和配置文件如何为 null?

发生的事情是我第一次获得非空用户,然后用户变为空(没有任何操作)不知道这怎么可能。因为我正在获取的用户来自 firebase,所以它不应该在没有任何操作的情况下改变

【问题讨论】:

  • 你的问题解决了吗?
  • @axtck 是的,我解决了我的问题。问题出在其他地方,但仅与此有关。所以我在做类似//do something; setUser(a); if(user == null) //do something; 的事情,问题是if(user==null) 总是正确的,因为 setUser 是异步的,不会立即设置用户。我引入了一个局部变量,它得到了修复

标签: reactjs react-native expo hybrid-mobile-app use-effect


【解决方案1】:

setState() 异步发生,这意味着当您 console.log() 变量时,变量仍然为空。您可以在 useEffect() 中等待状态更新,使用 useEffect() 作为对 setState() 的回调。

【讨论】:

    【解决方案2】:

    在 React 中,设置状态是异步的,所以如果你在下一行立即记录,你将无法看到更新后的状态。

    在这种情况下,您需要做的是在依赖数组中使用useEffectuser,以便在user 更改时采取措施。

        const fetchCurrentUser = async () => {
            let u = await firebase.auth().currentUser;
            setUser(u)
        }
    
        useEffect(() => {
            fetchCurrentUser();
        }, [])
    
        useEffect(() => {
          (async () => {
            if(user) { //to ensure that we only take actions if user is actually set
            console.log(user)
            let prof = await firebase.firestore().collection('abc').doc(u.uid).get();
            prof === null ? prof = await firebase.firestore().collection('efg').doc(u.uid).get() : null;
            setUserProfile(prof);
            console.log(u)
            console.log(prof)
            console.log(user)
            console.log(userProfile)
          })()
        }, [user]) //only trigger function when user state changes (and for first render)
    

    【讨论】:

    • 不能在非异步函数中使用 await
    • 嗯,对,会适当更新我的答案
    • 刚刚也编辑了我的问题(最后一行)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2018-07-16
    相关资源
    最近更新 更多