setState()的调用可能是异步的,如果像下面这样来计算下一个值可能是错误的:

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

要解决它,使用setState()接受函数而不是对象的第二种形式该函数将接收先前的状态作为第一个参数,并将应用更新时的props作为第二个参数:

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

当然箭头函数也可以像常规函数一样使用:

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-16
  • 2021-10-13
  • 2021-09-24
  • 2021-05-20
  • 2021-09-27
  • 2022-02-09
相关资源
相似解决方案