super()和super(props)的区别以及为什么要写super(props)

一般,我们在写自定义类组件的时候会写上构造函数如下:

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isOn: true };
  }
  // ...
}

当然,也可以像下面这样写:

class Checkbox extends React.Component {
  state = { isOn: true };
  // ...
}

当React 0.13在2015年增加对普通类的支持时,计划使用这样的语法。定义构造函数和调用super(props)成为临时解决方案,直到类字段提供符合人体工程学的替代方案。
但是,让我们回到这个例子,只使用ES2015功能:

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isOn: true };
  }
  // ...
}

**我们为什么调用super?我们可以不调用它吗?如果我们必须调用它,如果我们不传递props会发生什么?**还有其他论点吗?让我们来看看。

为什么要调用super(props)?

在JavaScript中,super指的是父类构造函数。(在我们的示例中,它指向React.Component实现。)

重要的是,在调用父构造函数之前,不能在构造函数中使用this。 JavaScript不会让你:

class Checkbox extends React.Component {
  constructor(props) {
    // ? Can’t use `this` yet
    super(props);
    // ✅ Now it’s okay though
    this.state = { isOn: true };
  }
  // ...
}

有一个很好的理由说明为什么JavaScript在你触摸它之前强制执行父构造函数。考虑一个类层次结构:

class Person {
  constructor(name) {
    this.name = name;
  }
}

class PolitePerson extends Person {
  constructor(name) {
    this.greetColleagues(); // ? This is disallowed, read below why
    super(name);
  }
  greetColleagues() {
    alert('Good morning folks!');
  }
}

想象一下,在允许调用super之前使用this。一个月后,我们可能会更改greetColleagues以在邮件中包含此人的姓名:

greetColleagues() {
    alert('Good morning folks!');
    alert('My name is ' + this.name + ', nice to meet you!');
}

在super调用之前,也就是父类的构造函数执行之前,调用greetColleagues去访问父类的name属性,这时候会出错。
为了避免这些陷阱,JavaScript强制要求:如果你想在构造函数中使用this,你必须首先调用super。让父级做自己的事!此限制也适用于定义为类的React组件:

constructor(props) {
    super(props);
    // ✅ Okay to use `this` now
    this.state = { isOn: true };
  }

为什么要传递props?

你可能认为将props传递给super是必要的,以便基本的React.Component构造函数可以初始化this.props:

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

这与事实并不遥远 - 事实上,这就是它的作用。

但不知何故,即使你没有使用props参数调用super,你仍然可以在render和其他方法中访问this.props。 (如果你不相信我,请亲自试试!)

这是如何运作的?事实证明,在调用构造函数后,React也会在实例上分配props

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

因此,即使你忘记将props传递给super,React仍会在之后设置它们。这是有原因的。
当React添加对类的支持时,它不仅仅增加了对ES6类的支持。目标是尽可能支持广泛的类抽象。目前尚不清楚ClojureScript,CoffeeScript,ES6,Fable,Scala.js,TypeScript或其他解决方案在定义组件方面的成功程度。所以React故意不关心是否需要调用super - 即使是ES6类。

那么这是否意味着你可以只写super()而不是super(props)?

尽可能不要这样,否则会使人困惑。

当然,React稍后会在你的构造函数运行后分配this.props。但是this.props在调用super和构造函数结束之间仍然是未定义的:

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

// Inside your code
class Button extends React.Component {
  constructor(props) {
    super(); // ? We forgot to pass props
    console.log(props);      // ✅ {}
    console.log(this.props); // ? undefined 
  }
  // ...
}

如果在从构造函数调用的某个方法中发生这种情况,则调试可能更具挑战性。 这就是为什么我建议总是传递super(props),即使它不是绝对必要的

class Button extends React.Component {
  constructor(props) {
    super(props); // ✅ We passed props
    console.log(props);      // ✅ {}
    console.log(this.props); // ✅ {}
  }
  // ...
}

这样可以确保在构造函数退出之前设置this.props。

为什么可以不写构造函数?

最后一点React用户可能会对此感到好奇。

您可能已经注意到,当您在类中使用Context API时(使用遗留的contextTypes或React 16.6中添加的现代contextType API),上下文将作为第二个参数传递给构造函数。

那么为什么我们不写super(props, context)呢?我们可以,但上下文的使用频率较低,所以这个陷阱并没有那么多。

随着类字段的提议,这整个陷阱大多数都会消失。如果没有显式构造函数,则会自动传递所有参数。这允许像state = {}这样的表达式包含对this.props或this.context的引用(如果需要)。
下面的例子中,依然会看到提示框显示name:

class Person {
  constructor(name) {
    this.name = name;
    alert(this.name);
  }
}

class PolitePerson extends Person {
 // constructor(name) {
 //       super(name);
 //  }
}

new App('zs');

有了Hooks,我们甚至没有super或this。但那是另一天的话题。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值