【问题标题】:React, Redux & Firestore variable availabilityReact、Redux 和 Firestore 变量可用性
【发布时间】:2019-12-03 19:37:45
【问题描述】:

在 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”变量。有没有什么办法可以在没有破解的情况下解决这个问题?

【问题讨论】:

    标签: reactjs react-redux google-cloud-firestore


    【解决方案1】:

    好的,所以这实际上可以通过您可以在 componentDidUpdate 生命周期方法而不是 componentDidMount 中进行的比较来解决。改编自答案 Re-render React component when prop changes

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

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

    在我的控制台中,我可以看到四个“Still waiting”,然后它最终转移到“Ok now we're good”

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2018-07-03
      • 2019-06-18
      • 2021-03-31
      • 2019-02-05
      相关资源
      最近更新 更多