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 }; });