【解決】React setState延遲delay導致數據更新不及時,代碼無法正確執行

之前React setState後在另一個函數調用state的值沒有更新:

 

// init state.type = 'new';

activeMenu(type) {
  // type = top
  if (type == this.state.type) return;
  this.loadList(type);
}

loadList(type) {
  this.setState({
    items: [],
    type: type
  });

  .........
  // type  is top, but this.state.type still is new
}

 

 

改進後的setState是這樣的:

 

// 使用setState的回調函數即可解決  
activeMenu(type) {
    if (type == this.state.type) return;
    this.setState({
      items: [],
      page: 1,
      type: type,
      isLoading: false,
      isLoadedFinished: false
    }, function() {
      this.loadList();
    });
  }

loadList() {
  // 這樣我們就可以愉快及時的使用 state裏面的值
  。。。
  。。。
}

 

 

 

有疑問或技術交流,掃描公衆號一起討論學習。

更多React在線學習訪問:http://each.sinaapp.com/react/index.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章