1 回答

TA贡献1851条经验 获得超5个赞
您可以使用一个类变量来跟踪您的组件是否已安装。那看起来像这样:
constructor() {
//...
this._mounted = false;
}
componentDidMount() {
this._mounted = true;
//...
}
componentWillUnmount() {
//...
this._mounted = false;
}
然后在异步请求后设置状态的任何地方,您可以放置一个 if 语句来检查是否_mounted为真。
在你的情况下:
getFirebaseData(refId) {
const database = firebase.database().ref(`workflows/sky/${refId}`);
database.on('value', snapshot => {
// Check if component is still mounted.
if (this._mounted) {
this.setState({ firebaseData: snapshot.val() });
}
}, error =>
console.log(error)
);
}
添加回答
举报