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
  };
});
相關文章
相關標籤/搜索