[译]React ES6 class constructor super()

发布时间:2019-08-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[译]React ES6 class constructor super()脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

当我们在写React时候 会用到ES6中的class语法 ,比较常见的情况如下:

class MyClass extends React.component{
    constructor(){
        suPEr()
    }
}

这里有两个问题:

  1. 是否有必要在constructor中调用super()函数?

  2. 调用super()super(PRops) 有何区别 ?

解答 Q1:

Always call super() if you have a constructor and don't worry about IT if you don't have a constructor

只有当你有一个constructor时候调用super()才是必须的 看代码:

class MyClass extends React.component{
    render(){
        return <div>Hello {this.props.world}</div>
    }
}

上述代码完全符合规定所以你其实并没有必要去为你创建的每个React Component 调用super() 话分两头 如果你的代码中有constructor你就必须调用super()

class MyClass extends React.component {
    constructor(){
        console.LOG(this) @H_303_126@//Error: 'this' is not Allowed before super()
    }
}

出现上述错误的原因 super() 未被调用之前 this 还未被初始化 (uninitialized) 了解更多
或许聪敏的你会想着 使用一个空的constructor从而摆脱super()

class MyClass extends React.component {
    constructor(){} // Error: missing super() call in constructor
}

ES6的 class 的constructors如果属于子类就 必须调用super()方法 所以一旦你的代码有
constructor 你就必须调用用 super()

解答Q 2:

Call super(props) only if you want to access this.props inside the constructor. React automatically set it for you if you want to access it anywhere else.

假使你想获取到constructor中的this.props 你就必须调用super(props) 然后React就会自动为你自动为你配置好它 以便你可以在随便什么地方调用它

看一下使用super() super(props) 的不同 :

class MyClass extends React.component{
    constructor(props){
        super();
        console.log(this.props); // this.props is undefined

    }
}

当使用super(props)时 你可以从constructor中获取到this.props

class MyClass extends React.component{
    constructor(props){
        super(props);
        console.log(this.props); // prints out whatever is inside props
    }
}

当然还有一点 当你想在其他地方使用它时 也没有必要将props传递到constructor中 React会自动为你设置好它 了解更多

class MyClass extends React.component{
    render(){
        // There is no need to call `super(props)` or even having a constructor 
        // this.props is automatically set for you by React 
        // not just in render but another where else other than the constructor
        console.log(this.props);  // it works!
    }
}

我的理解是 总之 需要绑定 this. 方法或是需要在 constructor 使用操作 props 定义 state,就需要 constructor ,否则 例如在其他方法中(如 render())使用 this.props 则没必要要使用 constructor

原文链接: React ES6 class constructor super()

脚本宝典总结

以上是脚本宝典为你收集整理的[译]React ES6 class constructor super()全部内容,希望文章能够帮你解决[译]React ES6 class constructor super()所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。