react官網說明setState不一定同步,state為component封裝內部狀態屬性,當呼叫setState()就會重新繪製,所以由react自己透過diff進行控制state更新狀態。所以再操作state時需注意取值方式和時機,setState()可以透過第二參數callback來取到更新後的值,或在lifecycle componentDidUpdate當UI更新完後再取值,才不會發生state已更新但取到的值依然是舊值。
src/StateDiff.js
import React, { Component } from 'react';
class StateDiff extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
counter: this.state.counter + 1
},
function(){
console.log('handleClick_fn:'+this.state.counter);
});
console.log('handleClick:'+this.state.counter);
}
componentDidUpdate() {
console.log('componentDidUpdate:'+this.state.counter);
}
render() {
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
}
export default StateDiff;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import StateDiff from './StateDiff';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<StateDiff /> ,
document.getElementById('root'));
registerServiceWorker();
輸出畫面(click觸發handleClick函數取到舊值0)
handleClick:0
componentDidUpdate:1
handleClick_fn:1
參考資料
Component State
https://reactjs.org/docs/faq-state.html