【发布时间】:2018-12-17 05:06:04
【问题描述】:
为什么会出现这个错误?
警告:无法在未安装的设备上调用 setState(或 forceUpdate) 零件。这是一个无操作,但它表明您的内存泄漏 应用。要修复,请取消所有订阅和异步任务 在 componentWillUnmount 方法中。
postAction.js
export const getPosts = () => db.ref('posts').once('value');
组件:
constructor(props) {
super(props);
this.state = { posts: null };
}
componentDidMount() {
getPosts()
.then(snapshot => {
const result = snapshot.val();
this.setState(() => ({ posts: result }));
})
.catch(error => {
console.error(error);
});
}
componentWillUnmount() {
this.setState({ posts: null });
}
render() {
return (
<div>
<PostList posts={this.state.posts} />
</div>
);
}
【问题讨论】:
-
卸载的组件没有状态,不需要这样做。 React 已经告诉你这是一个
no-op -
你不应该在
componentWillUnmount中调用this.setState。如果删除它,警告会消失吗? -
嘿,你可以在官方网站上阅读 react 生命周期钩子文档。它说当组件卸载时,不会进行任何状态更新,因为最终该组件的 UI 将被销毁
-
getPosts() 是异步方法。这就是错误。谢谢你们。谢谢@nicolas-tower
标签: javascript reactjs firebase