React, Redux & Firestore 变量可用性



在 React 的 componentDidMount 中,我从 Firestore 调用了一些数据,其中关联的 ID 与字符串匹配。硬编码,一切正常,我们使用this.props.addStore将数据添加到Redux存储中。

firebaseApp.firestore().collection('stores').where("associatedID", "==", "LFQ3eJZdbCUrziyoKTV1fVapa2E3").get().then((snapshot)=>{
    snapshot.docs.forEach(doc => {
    let store = doc.data();
    //Tell redux
    this.props.addStore(store);
});
}).then(()=>{
    console.log(this.props.user.associatedID);
});

但是,如果我们将该关联的 ID 作为从 Redux 中提取的变量,那么我们返回一个错误,即"where 的第三个参数未定义">

firebaseApp.firestore().collection('stores').where("associatedID", "==", this.props.user.associatedID)

但是在原始代码中,您会注意到在最终的.then函数中,有一个this.props.user.associatedID的控制台日志,它工作得很好。

这向我表明,Redux 应用要使用的组件的状态值存在轻微的延迟/错误排序/任何内容。或者通俗地说,组件只需要在 componentDidMount 中多一点时间,然后才能使用 'this.props.user' 变量。有什么方法可以在没有黑客的情况下解决这个问题吗?

好的,

所以这实际上是可以通过在componentDidUpdate生命周期方法而不是componentDidMount中进行的比较来解决的。改编自答案当道具更改时重新渲染 React 组件

componentDidMount 只是被调用得太早了(在组件可以访问 redux 状态之前(,所以对 firestore 的调用试图使用一个尚不存在的变量。通过检查组件每次更新的时间,我们可以看到它何时最终可以访问该变量。

componentDidUpdate(){
    if(this.props.user.associatedID){
        console.log("Ok now we're good");
    }
    else{
        console.log("Still waiting!");
    }
}

在我的控制台中,我可以看到四个"仍在等待",然后它最终移动到"好的,现在我们很好"

最后更新这实际上最好用ComponentWillReceiveProps(现已弃用(及其替代品getDerivedStateFromProps来解决。与在 ComponentDidUpdate 中一样,解决方案最终可能会被多次调用。而在getDerivedStateFromProps中,我们可以进行一次性比较并呼叫firestore。

最新更新