前言
在写React的时候,有时候会被constructor()搞懵,不知道什么时候该写super(),super(props)。现在来总结一下。
class
由于,React是依赖于es6的Class,就是es5对象的语法糖。里面的constructor想当于对对象的初始化。
例如:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let point = new Point(1,2);
point.x === 1 //true
point.y === 2 //true
constructor()
先说结论:
只要存在constructor就要调用super()
但是,不是每个react组件都需要constructor,比如下面的代码是可以正常运行的:
class App extends React.Component {
render() {
return (
<h1>{this.props.text}</h1>
);
}
}
很多时候需要在constructor中访问this:
constructor() {
console.log(this); --- Syntax error: 'this' is not allowed before super()
}
这是因为当没有调用super()时,this还没有被初始化,所以不能使用;那如果我不使用this呢?
constructor() {
--- Syntax error: missing super() call in constructor
}
es6会在语法层面强制你调用super(),所以得到的结论就是:<b>只要存在constructor就必须调用super()</b>
super()
第一个问题已经回答了什么时候调用super(),那什么时候必须要调用super(props)呢?先说结论:
当需要在constructor中访问<b>this.props</b>的情况下
从上面的代码可以看出,即使没有constructor,依然可以在render中使用this.props,这是因为react在初始化class后,会将props自动设置到this中,所以在任何地方都可以直接访问this.props,除了一个地方:<b>constructor</b>
constructor(props) {
super();
console.log(this.props); --- undefined
}
所以当你需要在constructor中访问this.props时,才需要设置super(props),
当然 可以直接使用props:
constructor(props){
super()
console.log('props',props)
}