React——为什么我们要写super(props)

本文总结自Dan Abramov博客

在编写react类组件的过程中,下面constructor中的代码我们应该已经见过无数次,但是却没有思考过为何必须这么去写:

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
}

在出现类属性的提案后,我们还可以这样去声明我们的state:

class Example extends Component {
    state = {
        isSwitchOn: false
    }
}

在解释为何要编写super(props)的时候,先回顾一下ES6中类的语法以及super的语义。在构造器constructor中,super()会执行父类的构造方法,在React类组件中就是Component类。而且在constructor构造器中有一个规定,那就是在super()调用前是不能够使用this的。

class Example extends Component {
    constructor(props) {
        console.log('You cannot use this here');
        super(props);
        console.log('You can use this now');
    }
}

这样规定的原因是父类构造器中可能会初始化一些属性,如果不调用super(),那么初始化的代码就不会执行,此时如果使用this获取父类中未初始化的属性就会是undefined。为了避免这种情况的发生,所以ES6规范强制要求我们在super()调用后使用this。

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

class Child extends Person {
    constructor() {
        console.log(this.name);  // undefined
        super('childName');
    }
}

回到我们的React类组件中,super(props)显然是调用了父类Component的构造器,而传入props的作用就是初始化props实例。

/**
 * Base class helpers for the updating state of a component.
 */
function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

上面代码摘自:React官方库

那么如果我们调用super(),但是不传入props。是不是意味着在整个类组件中都无法通过this获取props?也就是说this.props一直都是undefined?实际上并不是这样的。React会在调用构造函数后立即将props赋值到this上:

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

所以,在这种情况下,我们在constructor构造其中是无法通过this获取到props,但是在类的其他地方完全可以。

class Example extends Component {
    constructor(props) {
        super();
        console.log(this.props);  // undefined
        console.log(props);       // {}
    }
}

当然,如果使用react hook语法,也就不需要再关注这些了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值