【译】为何我们要写super(props)?

我听说现在Hooks是新的热点。讽刺地是,我想描述类的相关事实作为这片博客的开始。那是怎么样的呢?

这些坑对于有效地使用React并不重要。但如果你想更深入地了解事物的工作原理,你可能会发现它们很有趣。

这是第一个。


我的生命中我写的 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 };
    // ... 
}
复制代码

2015年React 0.13增加了对纯类的支持时,就计划了这样的语法。定义constructor函数和调用super(props)一直是一种临时解决方案,直到类字段提供了一种符合人体工程学的替代方案。

但是让我们回到这个例子,只使用ES2015特性:

class Checkbox extends React.Component {
    construtor(props) {
        super(props);
        this.state = { isOn: true };
    }
    // ...
}
复制代码

为何我们要调用super?我们可以不调用它吗?如果我们不得不调用它,不传props参数会发生什么呢?还存在其它的参数吗? 让我们一探究竟。

为何我们要调用 super?调用不当会发生什么呢?


在JavaScript中,super引用的是父类的constructor(在我们的例子中,它指向React.Component实现)。

重要的是,你不能使用this直到你调用父级的constructor后。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会强制父构造函数在你访问this之前运行。考虑一个类层次结构:

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 forks!');
    }
}
复制代码

想象一下thissuper之前被调用是被允许的。一个月后,我们可能改变greetColleagues中包含在person中的信息:

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

但是我们忘记了super()在有机会设置this.name之前调用了this.greetemployees(),因此this.name都还没定义。正如你所看到的一样,很难思考像这样的代码。

为了避免这样的坑,JavaScript会迫使你在使用this之前先调用super. 让父级做它该做的事情!这个限制也适用于定义为类的React组件:

construtor(props) {
    super(props);
    // ✅ Okay to use `this` now
    this.state = { isOn: true };
}
复制代码

这里还存在另外一个问题:为什么要传递props?


你也许认为传递propssuper是必要的,这样React.Component构造函数就能初始化this.props了:

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}
复制代码

这与事实相去不远——确实,事实就是如此

但是,即使你调用super没带props参数,你依然可以在render或者其它方法中获取到props。(如果你不信我,你可以自己试试!)

那到底是怎样工作的呢?事实表明 React也会在调用构造函数后立即在实例上初始化props:

// Inside React
const instance = new YourComponent(props);
instance.props = props;
复制代码

因此即使你忘记了给super传递propsReact也会立即设置它们。这是有原因的。

当React添加了对类的支持时,它不仅仅只支持ES6中的类。目标是支持尽可能广泛的类抽象。目前还不清楚使用ClojureScript,CoffeeScript,ES6,Fable,Scala.js,TypeScript,或者其它方式定义组件会有多成功。因此,React故意不明确是否需要调用super()——即使ES6的类需要。

所以这就意味着你可以使用super()代替super(props)了吗?

可能不是因为它仍然令人困惑。 当然,React会在你运行了constructor之后为this.props赋值。但是在super调用和构造函数结束之间,this.props仍然是未定义的:

// Inside React
class Component {
    construtor(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); // ✅ {}
    }
}
复制代码

保证在constructor存在之前this.props就被设置了。


还有最后一点React用户可能会感到好奇的。

你可能注意到在类中使用Context API时(包括旧的contextTypes和在React16.6中添加的现代contextType API),context作为第二个参数被传给constructor

为什么我们不用super(props, context)代替呢?我们能够,只是上下文的使用频率较低,所以这个坑不会经常出现。

随着类字段的提议,这个坑基本上消失了。 如果没有显式构造函数,所有参数都将被自动传递下去。这就是允许像state ={}这样的表达式包含对this.props或者this.context的引用的原因。

使用Hooks,我们甚至不会使用到super或者this。但是那是下次的话题。

原文链接:overreacted.io/why-do-we-w… by Dan Abramov

转载于:https://juejin.im/post/5c0f7ca551882516be2f011e

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值