ReactJS concurrent SetState race condition

我的未来我决定 提交于 2019-12-04 05:50:22

You probably want to pass a function to setState which should remove such race conditions. Something like:

this.setState(currentState => {
  currentState.someProp++;
  return currentState;
});

Even if two different parts of your application does this at the same time, both functions will still be called and someProp will be incremented twice.

If you were to do this instead: this.setState({someProp: this.state.someProp + 1}) it would only be incremented once because this.state.someProp isn't updated directly after calling setState. But when passing a function to setState you get the current pending state as an argument, which gives you the option to either just increment like in my example, or merge your mutation with any other mutation that took place.

According to React documentation, as mentioned in the first answer, you can pass a function to ensure the atomicity's operation. The thing is that you should not modify the state but return the new value inside the passed function:

setState(function(previousState, currentProps) {
  return {myInteger: previousState.myInteger + 1};
});

https://facebook.github.io/react/docs/component-api.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!