解決React通過ajax加載數據更新頁面不加判斷會報錯的問題


通過AJAX加載數據是一個很普遍的場景。在React組件中如何通過AJAX請求來加載數據呢?首先,AJAX請求的源URL應該通過props傳入;其次,最好在componentDidMount函數中加載數據。加載成功,將數據存儲在state中后,通過調用setState來觸發渲染更新界面。

AJAX通常是一個異步請求,也就是說,即使componentDidMount函數調用完畢,數據也不會馬上就獲得,瀏覽器會在數據完全到達后才調用AJAX中所設定的回調函數,有時間差。因此可以使用 componentWillUnmount 來取消任何未完成的請求;

componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  },
 
  componentWillUnmount: function() {
    this.serverRequest.abort();
  }

官網是這么解釋的

When fetching data asynchronously, use componentWillUnmount to cancel any outstanding requests before the component is unmounted.

 

當異步加載數據的時候, 使用 componentWillUnmount 來取消任何未完成的請求 在組件卸載之前

 

 componentWillUnmount()

 

在組件從 DOM 中移除的時候立刻被調用。

在該方法中執行任何必要的清理,比如無效的定時器,或者清除在 componentDidMount 中創建的 DOM 元素

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM