react警告:setState(...): Cannot update during an existing state transition (such as within `render` or

在使用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
}

警告就没有了

猜你喜欢

转载自blog.csdn.net/Two_Too/article/details/82689515