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



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值