加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React Ajax this.IsMounted() is not a function

发布时间:2020-12-15 03:30:34 所属栏目:百科 来源:网络整理
导读:大概是这样的代码 $.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
            });
        }
    }
});

然后浏览器报了这样一个错


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,usecomponentWillUnmountto cancel any outstanding requests before the component is unmounted.


当异步加载数据的时候, 使用 componentWillUnmount来取消任何未完成的请求 在组件卸载之前

componentWillUnmount()

在组件从 DOM 中移除的时候立刻被调用。

在该方法中执行任何必要的清理,比如无效的定时器,或者清除在componentDidMount中创建的 DOM 元素

所以我们可以用这个方法替代 isMounted() 来确保该组件是否还是mounted

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读