1. 程式人生 > >React Ajax this.IsMounted() is not a function

React Ajax this.IsMounted() is not a function

大概是這樣的程式碼

$.ajax({
    ...
    success: function(data) {
        var quote = data[0].media;
        if (this.isMounted()){
            this.setState({
                quotes: quote
            });
        }
    }
});

 然後瀏覽器報了這樣一個錯

 this.IsMounted() is not a function

然後我谷歌的找到了其他人的回答

大概是這樣的

$.ajax({
    ...
    success: function(data) {
        var quote = data[0].media;
        if (this.isMounted()){
            this.setState({
                quotes: quote
            });
        }
    }.bind(this);
});

或者是這樣的

componentDidMount: function(){
    $.ajax({
      // the method is already bound to the component
      success: this.onDataReceived
    });
  },

  onDataReceived: function(data) {
    var quote = data[0].media;
    if(this.isMounted()){
      this.setState({
        quotes: quote
      });
    }
  }
這些程式碼主要說的是 this 指標指向不對,但是我按照這樣修改之後,發現仍舊報了這樣的錯誤。

對比了一下React中文api和阮一峰大神的demo,確實都是這樣寫的。為啥會錯?

隨即去翻了React官網的API,原來 isMounted() 這個方法被React廢棄掉了,so 不能用這個函數了

然後官網給了一個案例

大概是這個樣子的

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 元素

所以我們可以用這個方法替代 isMounted() 來確保該元件是否還是mounted