在使用react的时候,发现一个警告
Warning: setState(...):Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`
不能在现有状态转换期间更新(例如在' render '或其他组件的构造函数中)。渲染方法应该是道具和状态的纯函数;构造函数的副作用是反模式的,但是可以移动到“componentWillMount”
先开始我是这样写的:
componentDidMount(){
AccountStore.listen(this.accountChange);
this.accountChange();
}
然后在运行的时候,偶尔会出现警告:

setState是异步执行的,加一个this.mounted控制执行顺序:
componentDidMount(){
this.mounted = true;
AccountStore.listen(this.accountChange);
if(this.mounted == true){
this.accountChange();
}
}
componentWillUnmount(){
this.mounted = false
}
警告就没有了

本文探讨了在React中遇到的一个警告,即在渲染或组件构造函数中调用setState。解释了为什么这是一个反模式,并提供了一个解决方案,通过在componentDidMount中检查一个布尔变量mounted来确保setState在适当的时机被调用。

被折叠的 条评论
为什么被折叠?



