javascript - How to stop Firestore `get` query on componentWillUnmount
问题描述
okay so I'm fetching data from Firestore in componentDidMount but while it's fetching the data if I change the component I get error saying:
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
In Firebase real time database we call ref.off()
to stop query.
Wondering how to do it in Firestore
componentDidMount() {
Users.get().then(({ docs }) => {
const users = docs.map(user => user.data());
this.setState({ users });
});
}
componentWillUnmount(){
}
解决方案
如果有人仍在寻找答案,我找到了一种解决方法:
componentDidMount() {
this.mounted = true;
Users.get().then(({ docs }) => {
const users = docs.map(user => user.data());
if(this.mounted) this.setState({ users });
});
}
componentWillUnmount(){
this.mounted = false;
}
this.mounted
当组件被卸载并且 setState 将不起作用时将为 false。
推荐阅读
- java - 如何读取库内的spring boot应用程序属性信息
- regression - Stata Probit 模型交互项解释
- amazon-web-services - 弹性 beantalk 内的网络服务器提供空页面。“加载资源失败:net::ERR_CONNECTION_TIMED_OUT”
- docker - 将 Mattermost 从 release-5.29 更新到 release-5.33 破坏了我的体积数据
- lightningchart - 获取轴内的所有系列并使用 min max 设置间隔
- python - 为什么创建我自己的自定义错误页面 (400) 会导致带有有效 url 的服务器错误?
- google-chrome-extension - Chrome 扩展显示页面操作示例清单 v3
- excel - Excel 函数在 COMBIN() 中返回嵌套的 SEQUENCE
- python - Python数据框为具有先前日期时间的每个唯一ID减去日期时间并放入单独的列
- python - 使用 hvplot 时出现奇怪的错误“没有为此条目加载插件:xarray_image”