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.
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!
}
}
当我们在写React时候 会用到ES6中的class语法 ,比较常见的情况如下:
这里有两个问题:
是否有必要在
constructor
中调用super()
函数?调用
super()
和super(props)
有何区别 ?解答 Q1:
只有当你有一个
constructor
时候调用super()才是必须的 看代码:上述代码完全符合规定所以你其实并没有必要去为你创建的每个React Component 调用
super()
话分两头 如果你的代码中有constrctor
你就必须调用super()
出现上述错误的原因是
super()
未被调用之前this
还未被初始化 (uninitialized) [更多] 或许聪敏的你会想着 使用一个空的constructor
从而摆脱super()
ES6的
class
的constructors如果属于子类就 必须调用super()
方法 所以一旦你的代码有constructor
你就必须调用用super()
解答Q 2:
假使你想获取到
constructor
中的this.props
你就必须调用super(props)
然后React就会自动为你自动为你配置好它 以便你可以在随便什么地方调用它看一下使用
super()
和super(props)
的不同 :当使用
super(props)
时 你可以从constructor
中获取到this.props当然还有一点 当你想在其他地方使用它时 也没有必要将props传递到constructor中 React会自动为你设置好它 [更多]
我的理解是 总之 需要绑定
this.
方法或是需要在 constructor 使用操作 props 定义 state,就需要 constructor ,否则 例如在其他方法中(如render()
)使用 this.props 则没必要要使用 constructor原文链接: React ES6 class constructor super()