State 的更新可能是异步的

出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用。

因为 this.props 和 this.state 可能会异步更新,所以你不要依赖他们的值来更新下一个状态。

例如,此代码可能会无法更新计数器:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

要解决这个问题,可以让 setState() 接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:

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

上面使用了箭头函数,不过使用普通的函数也同样可以:

// Correct
this.setState(function(state, props) {
  return {
    counter: state.counter + props.increment
  };
});

 

相关文章:

  • 2023-04-09
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2022-12-23
  • 2021-07-21
  • 2022-12-23
  • 2021-11-06
猜你喜欢
  • 2022-01-18
  • 2022-02-02
  • 2022-12-23
  • 2022-12-23
  • 2021-08-03
  • 2021-06-06
  • 2021-10-10
相关资源
相似解决方案