React中this.setState的异步性质

Lea*_*ath 6 javascript asynchronous reactjs

假设我有这两个电话:

 this.setState((prevState, props) => ({
    counter: prevState.counter + props.increment
 }));

 this.setState((prevState, props) => ({
    counter: prevState.counter + props.increment + 1
 }));
Run Code Online (Sandbox Code Playgroud)

因为setState是异步的,所以如何保证第一次调用它会先执行?

sam*_*j90 5

从 setState() 的反应文档中可以看出

setState() 组件状态的更改加入队列,并告诉 React 该组件及其子组件需要使用更新后的状态重新渲染。setState()也是异步的,同一周期内的多个调用可能会批量在一起。例如,如果您尝试在同一周期内多次递增或添加计数器的值,则将导致相当于:

Object.assign(
  previousState,
  {counter: previousState.counter + props.increment},
  {counter: previousState.counter + props.increment + 1},
  ...
)
Run Code Online (Sandbox Code Playgroud)

后续调用将覆盖同一周期中先前调用的值,因此数量只会增加一次。如果下一个状态取决于当前状态,我们建议使用更新函数形式:

this.setState((state) => {
  return {counter: state.counter + 1};
});
Run Code Online (Sandbox Code Playgroud)