[英]Can't perform a React state update on an unmounted component with firebase firestore
so.. i tried some similar answer here but non of theme work, and need to listen to live update from firestore db and i have to work with class component所以..我在这里尝试了一些类似的答案,但不是主题工作,需要收听来自 firestore db 的实时更新,我必须使用 class 组件
always get this warning:总是收到此警告:
Can't perform a React state update on an unmounted component.
无法对未安装的组件执行 React state 更新。 This is a no-op, but it indicates a memory leak in your application.
这是一个空操作,但它表明您的应用程序中存在 memory 泄漏。 To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
要修复,请取消 componentWillUnmount 方法中的所有订阅和异步任务。
my code:我的代码:
class Exchange extends React.Component {
constructor(props) {
super(props);
this.state = {
exchangePrice: 0,
newExchangePrice: "",
};
this.updateExchangePrice = this.updateExchangePrice.bind(this);
}
updateExchangePrice() {
const docRef = doc(db, "exchange", "exchange");
if (
this.state.newExchangePrice !== "" &&
this.state.newExchangePrice !== 0
) {
updateDoc(docRef, {
exchange_price: Number(this.state.newExchangePrice),
});
this.setState({ newExchangePrice: "" });
}
}
componentDidMount() {
const exchanges = collection(db, "exchange");
onSnapshot(exchanges, (x) => {
x.docs.forEach((doc) => {
if (doc.data().exchange_price !== this.state.exchangePrice) {
this.setState({ exchangePrice: doc.data().exchange_price });
}
});
});
}
Memory leaks is an issue when implementing React code, when using side-effects. Memory 泄漏是在使用副作用时实现 React 代码时的一个问题。 Explore more on this from here .
从此处探索更多相关信息。 Some side-effects require clean-up.
一些副作用需要清理。 And that clean-up can be done by the use of ComponentWillUnmount() life-cycle method in a class based component in React.
并且可以通过在 React 中基于 class 的组件中使用 ComponentWillUnmount() 生命周期方法来完成清理。 Using the ComponentWillUnmount() method, you can do the necessary un-subscriptions there that you previously implemented.
使用 ComponentWillUnmount() 方法,您可以在那里执行您之前实现的必要的取消订阅。
You may have a look at the React official doc to explore more on the method.您可以查看 React 官方文档以探索有关该方法的更多信息。
Also, you may have a look at the Stackoverflow case .此外,您还可以查看Stackoverflow 案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.