react组件中的constructor和super小知识

react组件中的constructor和super小知识

 

一、react中用class申明的类一些小知识

如上图:类Child是经过class关键字申明,而且继承于类React。html

A、Child的类型是?   typeof  Child   ===  'function'  , 其实就至关于ES5用function申明的构造函数    function Child() {  //申明构造函数  }react

B、Child类调用时候(  new Child() ),会优先执行,而且自动执行Child的constructor函数es6

constructor() {
   console.log('执行了constructor')
       return 'hah'
   }

   getName() {
       console.log('执行了方法')
   }
}
var dd = new Person();
console.log(dd)

打印以下:函数

三、Child类中的this?    this指向Child的实例,至关于 new Child()   那么它们彻底相等吗?  不是的,react中的this是在new Child()基础上进行了包裹(下图)post

             上图为new Child()      下图为 Child中的thisthis

 

结论:this是在new Child()基础上进行了包裹,包含了一些react内部方法,url

同时组件中使用Child类(  <div>  <Child /> </div> ),能够当作 new Child() + react包裹。(细节待追究。。。)spa

 

二、组件中的constructor是否有必要? 若是没有呢??做用呢???

ES6的知识补充:  http://es6.ruanyifeng.com/#docs/class-extends   以下:code

 

class ColorPoint extends Point {
}

// 等同于 
class ColorPoint extends Point {
  constructor(...args) {
    super(...args);
  }
}
// 可见没有写constructor,在执行过程当中会自动补上

 

由ES6的继承规则得知,无论子类写不写constructor,在new实例的过程都会给补上constructor。component

因此: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,那么为何不使用 无状态组件(建议使用) 呢???

 

三、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

下面是一个使用props的场景,此时别忘了 componentWillReceiveProps 生命周期哟

参考另外一篇文章  react的生命周期须要知道的

 

接上:若是constructor中不经过super来接收props,在其余生命周期,

诸如componentWillMount、componentDidMount、render中能直接使用this.props吗??

结论:能够的,react在除了constructor以外的生命周期已经传入了this.props了,彻底不受super(props)的影响

 

因此super中的props是否接收,只能影响constructor生命周期可否使用this.props,其余的生命周期已默认存在this.props

相关文章
相关标签/搜索