關於this.setState更新的問題

this.setState是異步,因此在this.setState以後當即調用this.state是獲取不到最新的數據的,那麼怎麼獲取最新的數據呢?下面介紹三個方法:異步

1.回調函數callback函數

this.setState({
  val: this.state.val+1
}, () => {
  console.log(this.state.val)
});

2.componentDidUpdatethis

componentDidUpdate(){
    console.log(this.state.val);
}

在this.setState以後去componentDidUpdate函數中調用,此時的this.state已經更新code

3.將this.setState放入setTimeout函數中component

let self = this;
setTimeout(function () {
  self.setState({
    val:self.state.val+1
  });
  console.log(self.state.val);
})

在setTimeout函數中,在this.setState以後this.state是當即更新的,因此也能夠獲取到更新後的數據。回調函數

相關文章
相關標籤/搜索