在React的componentDidMount中,我从associatedID匹配字符串的Firestore中调用一些数据。硬编码,一切正常,我们使用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);
});
但是,如果要将该associatedID作为从Redux中提取的变量,那么我们将返回一个错误,即“where的第三个参数是未定义的”
firebaseApp.firestore().collection('stores').where("associatedID", "==", this.props.user.associatedID)
但是在最初的代码中,您会注意到在最终的.then函数中,有一个this.props.user.associatedID的控制台日志,它工作得很好。
这表明Redux在应用组件要使用的状态值时存在轻微的延迟/乱序/任何情况。或者从外行人的角度来说,组件在componentDidMount中需要更多的时间才能使用'this.props.user‘变量。有什么办法不用黑我就能绕过这件事吗?
发布于 2019-07-25 06:50:05
好的,这实际上是可以通过比较componentDidUpdate生命周期方法而不是componentDidMount来解决的。改编自答案Re-render React component when prop changes
componentDidMount只是被调用得太快(在组件访问redux状态之前),所以对防火墙的调用试图使用一个还不存在的变量。通过每次检查组件更新,我们可以看到它何时最终获得对该变量的访问权。
componentDidUpdate(){
if(this.props.user.associatedID){
console.log("Ok now we're good");
}
else{
console.log("Still waiting!");
}
}
在我的控制台里,我可以看到四个“还在等着”,然后它终于转到“好了,我们好了”。
最终更新--实际上最好用ComponentWillReceiveProps (现在不再推荐)和它的替代getDerivedStateFromProps来解决。就像在ComponentDidUpdate中一样,解决方案最终可能会被多次调用。然而,在getDerivedStateFromProps中,我们可以进行一次比较,并呼叫消防局。
https://stackoverflow.com/questions/57203423
复制相似问题