react 组件中的 constructor 和 super 小知识
个人心得:不管子类写不写 constructor,在 new 实例的过程都会给补上 constructor。constructor 如果不写,无法声明 state。如果写了 constructor 不实现 super,获取不到 this。constructor 中的 props 不实现不会影响其他生命周期的使用,只会影响 constructor 构造函数里的使用。
1、react 中用 class 申明的类一些小知识
如上图:类 Child 是通过 class 关键字申明,并且继承于类 React。
A、Child 的类型是? typeof Child === 'function'
, 其实就相当于 ES5 用 function 申明的构造函数
function Child() { // 申明构造函数 }
B、Child 类调用时候( new Child() ),会优先执行,并且自动执行 Child 的 constructor 函数。
constructor() {
console.log('执行了constructor')
return 'hah'
}
getName() {
console.log('执行了方法')
}
}
var dd = new Person();
console.log(dd)
打印如下:
3、Child 类中的 this? this 指向 Child 的实例,相当于 new Child() 那么它们完全相等吗? 不是的,react 中的 this 是在 new Child() 基础上进行了包裹(下图)。
上图为 new Child(),下图为 Child 中的 this
结论:this 是在 new Child() 基础上进行了包裹,包含了一些 react 内部方法,同时组件中使用 Child 类 <div> <Child /> </div>
,可以看成 new Child() + react 包裹。
2、组件中的 constructor 是否有必要? 如果没有呢?作用呢?
ES6 的知识补充: http://es6.ruanyifeng.com/#docs/class-extends
class ColorPoint extends Point {
}
// 等同于
class ColorPoint extends Point {
constructor(...args) {
super(...args);
}
}
// 可见没有写 constructor,在执行过程中会自动补上
由 ES6 的继承规则得知,不管子类写不写 constructor,在 new 实例的过程都会给补上constructor,所以:constructor钩子函数并不是不可缺少的,子组件可以在一些情况略去。接下来,继续看下有没 有 constructor 钩子函数有什么区别:
A、先看有无 constructor 钩子函数的 this.constructor
有 constructor 钩子函数的 this.constructor
无 constructor 钩子函数的 this.constructor
如果能看细节的话,会得知有 constructor 钩子函数时候,Child 类会多一个 constructor 方法。
B、再看有无先看有无 constructor 钩子函数的 this,也就是组件实例。
有 constructor 钩子函数的 this 实例。
无 constructor 钩子函数的 this 实例。
会得知有 constructor 钩子函数时候,可以定义 state,如果用户不定义 state 的话,有无 constructor 钩子函数时候没有区别。
结论: 如果组件要定义自己的 state 初始状态的话,需要写在 constructor 钩子函数中,如果用户不使用 state 的话,纯用 props 接受参数,有没有 constructor 钩子函数都可以,可以不用 constructor 钩子函数。 再者如果 不使用 state,那么为什么不使用 无状态组件(建议使用) 呢?
3、super 中的 props 是否必要? 作用是什么??
有的小伙伴每次写组件都会习惯性在constructor和super中写上props,那么这个是必要的吗??
如图:
首先要明确很重要的一点就是:
可以不写 constructor,一旦写了 constructor,就必须在此函数中写 super(),此时组件才有自己的 this,在组件的全局中都可以使用 this 关键字,否则如果只是 constructor 而不执行 super() 那么以后的 this 都是错的!
来源 ES6 : http://es6.ruanyifeng.com/#docs/class-extends
但是 super 中必须写参数 props 吗?答案是不一定,先看代码:
有 props:
无 props:
可以得出结论:当想在 constructor 中使用 this.props 的时候,super 需要加入(props),此时用 props 也行,用 this.props 也行,他俩都是一个东西。(不过 props 可以是任意参数,this.props 是固定写法)。
如图:
如果在 custructor 生命周期不使用 this.props 或者 props 时候,可以不传入 props。
接上:如果 constructor 中不通过 super 来接收 props,在其他生命周期,诸如 componentWillMount、componentDidMount、render 中能直接使用 this.props 吗??
结论:可以的,react 在除了 constructor 之外的生命周期已经传入了 this.props 了,完全不受 super(props) 的影响。
所以 super 中的 props 是否接收,只能影响 constructor 生命周期能否使用 this.props,其他的生命周期已默认存在 this.props
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论