react es5的isMounted在es6中不支持,请问有什么解决办法

es5中

componentDidMount: function() {
    $.get(this.props.source, function(result) {
      if (this.isMounted()) {
        this.setState({
          ...
        });
      }
    }.bind(this));
  }

报错信息:Warning: isMounted(...) is deprecated in plain JavaScript React classes. Instead

问题1:请问componentDidMount方法在es6中是否应写在constructor里,还是单独写一个方法?
问题2: this.isMounted es6语法不支持(网上的说法是es6不支持autobind),请教高玩有没有什么替代办法?

阅读 9.6k
4 个回答

楼上的范例是正确的,以下附加说明。

用一个state中的值来判断是正确的作法。利用组件的将挂载或已挂载生命周期来变动这个值。

componentDidMount() {
    this.mounted = true;
}

componentWillUnmount() {
    this.mounted = false;
}

isMounted此方法已经弃用很久了,主要的原因是它经过实际使用与测试可能不足以检测组件是否挂载,尤其是对于有一些异步的程序情况,以及逻辑上造成混乱。setState本身可以提供一些错误的检查,不需要这个isMounted先作检查。参考: https://facebook.github.io/re...https://github.com/facebook/r...

componentDidMount是生命周期方法,继承得来的,所以独立写出来。

componentDidMount我是不写在constructor里的,但是这种写法算不算es6我就不知道了

this.isMounted不能用我也是今天才知道,因为我一直都是在constructor里面写一个this.mounted=true来标志component的状态的

例子

class OneClass extends React.Component{
    constructor(props){
        super(props)
        this.mounted = true
        this.state={}
    }
    
    componentWillUnmount(){
        this.mounted = false
    }
    
    componentDidMount(){
        //这个函数我写这里
    }
    
    render(){
        return()
    }
}

另外我还是建议用react就不要用jquery了,只是一个ajax并不需要引入jquery

嗯 我也用的 this.isUnmount = false

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题