javascript

为什么要写super(props)

2020-05-22  本文已影响0人  一蓑烟雨任平生_cui

用React开发class组件时,constructor中一定要调用 super(props)

下面通过两个问题逐步分析。第一:为什么要调用super?第二:为什么要传入props,不传会发生什么?

首先解释第一个问题:

在 JavaScript 子类的构造函数中 super 指的是父类(即超类)的构造函数。子类中显式定义了constructor的方法中必须在其最顶层调用super,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。所以必须先调用super才可以使用this。如果子类没有定义constructor方法,这个方法会被默认添加。

如下:

class A {}

class B extends A {
  constructor() {
    super()
  }
}

new B().constructor === B // true

以上结论证明super虽然代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B的实例,因此super()相当于A.prototype.constructor.call(this)

再通过 new.target 验证:

class A {
  constructor() {
    console.log(new.target.name);
  }
}

class B extends A {
  constructor() {
    super()
  }
}

new B() // B

new.target指向new命令作用的构造函数,以上 new.target.name 为 B,由此可知在super()执行时,它指向的是子类B的构造函数,而不是父类A的构造函数。也就是说,super()内部的this指向的是B。

在React中,super指向了 React.Component,所以在调用父类的构造函数之前,是不能在 constructor 中使用 this 关键字的。

class Button extends React.Component {
  constructor() {
    // 还不能访问 `this`
    super();
    // 可以访问
    this.state = { show: true }
  }
  // ...
}

第二个问题,为什么要传props?

为了让 React.Component 构造函数初始化 this.props。React源码是这样的:

function Component(props, context) {
  this.props = props;
  this.context = context;

  // ...
}

但是有些时候在调用 super() 的时即使没有传入 props,依然能够在 render 函数或其他方法中访问到 this.props。那这是怎么做到的呢?事实证明,React 在调用构造函数后也立即将 props 赋值到了实例上:

// React 内部
const instance = new YourComponent(props);
instance.props = props;

所以即便忘记了将 props 传给 super(),React 也仍然会在之后将它定义到实例上。这样做是有原因的:

当 React 增加了对类的支持时,不仅增加了对ES6类的支持。其目标是尽可能广泛的支持类抽象。当时尚不清楚 ClojureScript,CoffeeScript,ES6,Fable,Scala.js,TypeScript 或其他解决方案在类组件方面是否成功。因此 React 刻意地没有显式要求调用 super()。

那是不是意味着能够用 super() 代替 super(props) 吗?

最好不要这样做,这样写在逻辑上并不能确定没问题,因为React 会在构造函数执行完毕之后才给 this.props 赋值。但这样做会使得 this.props 在 super 调用一直到构造函数结束期间值为 undefined。

class Button extends React.Component {
  constructor(props) {
    super();  // 忘了传入 props
    console.log(props);      // {}
    console.log(this.props); // undefined
  }
  // ...
}

如果在构造函数中调用了内部的其他方法,那么一旦出错这会使得调试过程阻力变大。这就是为什么建议开发者一定执行 super(props) 的原因。

class Button extends React.Component {
  constructor(props) {
    super(props) // 传入 props
    console.log(props)      // {}
    console.log(this.props) // {}
  }

  // ...
}

这样就确保了 this.props 在构造函数执行完毕之前已被赋值。

此外,还有一点是 React 开发者长期以来的好奇之处。

当在组件中使用Context API 的时候,context会作为第二个参数传入constructor,那么为什么我们不写成 super(props, context) 呢?可以,但 context 的使用频率较低,因而没有必要。

而且 class fields proposal 出来后,在没有显示定义构造函数的情况下,以上属性都会被自动地初始化。使得像 state = {} 这类表达式能够在需要的情况下引用 this.propsthis.context 的内容:

class Button extends React.Component {
  state = {
    age: this.props.age,
    name: this.context.name
  }

  // ...
}

当然,有了 Hooks 以后,几乎就不需要 super 和 this 了,但那就是另一个概念了。

上一篇下一篇

猜你喜欢

热点阅读