.

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.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});

 

posted @ 2017-03-21 10:11  荆--棘  阅读(152)  评论(0编辑  收藏  举报