在React构造函数中调用super()做什么?

What does calling super() in a React constructor do?

本文关键字:什么 super React 构造函数 调用      更新时间:2023-09-26

从文档中学习React,遇到了这个例子:

class Square extends React.Component {
  constructor() {
    super();
    this.state = {
      value: null,
    };
  }
  ...
}

根据Mozilla, super允许你在构造函数中使用this。是否有其他理由使用独立的super(我知道super允许您访问父类的方法),但与React有任何其他用例只是调用super()本身?

super()将调用其parent类的constructor。当你需要从父类访问一些变量时,这是必需的。

在React中,当你用props调用super时,React会通过this.props使props在整个组件中可用。参见下面的示例2

不含super()

class A {
  constructor() {
    this.a = 'hello'
  }
}
class B extends A {
  constructor(){
    console.log(this.a) //throws an error
  }
}
console.log(new B())

with super()

class A {
  constructor(props) {
    this.props = props
  }
}
class B extends A {
  constructor(props) {
    super(props)
    console.log(this.props)
  }
}
console.log(new B({title: 'hello world'}))

super()只有在react组件中有构造函数时才会被调用。例如,下面的代码不需要super:

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

然而,如果我们有一个构造函数,那么super()是强制性的:

class App extends React.component {
    constructor(){
        console.log(this) //Error: 'this' is not allowed before super()
    }
}

this不能在super()之前被允许的原因是如果super()没有被调用,this是未初始化的。然而,即使我们不使用this,我们也需要在构造函数中使用super(),因为ES6 class constructors MUST call super if they are subclasses。因此,只要有构造函数,就必须调用super()。(但是子类不一定要有构造函数)

如果必须使用this.props,则在构造函数内部调用super(props),例如:

class App extends React.component{
    constructor(props){
        super(props);
        console.log(this.props); // prints out whatever is inside props
    }
}
我希望我能说清楚。

值得补充的是,super()是超类构造函数的缩写,是继承的一个概念。

默认情况下,类Square从它的超类React.Component继承构造函数。

继承的构造函数可以通过声明一个新的constructor()方法来重写。

如果目的是扩展而不是覆盖超类构造函数,那么必须使用super()显式调用它。

在实现React.Component subclass的构造函数时,应该在任何其他语句之前调用super(props)。否则,this.props将在构造函数中变为undefined,这可能会导致错误。

在JavaScript中,super指的是父类的构造函数。

重要的是,在调用父构造函数之前,不能在构造函数中使用this。JavaScript不会让你:但是我们忘记了,如果在super()调用有机会设置this.name之前调用函数。所以this。name还没有定义!正如您所看到的,这样的代码很难理解。为了避免这样的陷阱,JavaScript强制规定,如果想在构造函数中使用this,必须先调用super。让父母做自己的事吧!这个限制也适用于定义为类的React组件:

super();react不需要,但ES6子类

强制

要使用this关键字,我们应该在它之前使用super关键字。为什么?super用于调用父类的constructor

为什么我们需要调用父节点的constructor呢?答案是初始化我们通过this关键字引用的属性值。