react setState

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

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

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

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

固然箭头函数也能够像常规函数同样使用:this

this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});
相关文章
相关标签/搜索