(本文摘抄)
有的小伙伴每次写组件都会习惯性在constructor和super中写上props,那么这个是必要的吗??
![](https://img.haomeiwen.com/i12442612/8dc6d5572e2448c6.png)
首先要明确很重要的一点就是:
可以不写constructor,一旦写了constructor,就必须在此函数中写super(),
此时组件才有自己的this,在组件的全局中都可以使用this关键字,
否则如果只是constructor 而不执行 super() 那么以后的this都是错的!!!
来源ES6 : http://es6.ruanyifeng.com/#docs/class-extends
![](https://img.haomeiwen.com/i12442612/c4b1199ea76175cd.png)
但是super中必须写参数props吗?? 答案是不一定,先看代码:
有props:
![](https://img.haomeiwen.com/i12442612/b97dede9703bd183.png)
![](https://img.haomeiwen.com/i12442612/3073acdb24fe90dd.png)
无props:
![](https://img.haomeiwen.com/i12442612/3cfae60eb233c29b.png)
![](https://img.haomeiwen.com/i12442612/809996b470f490d7.png)
可以得出结论:****当想在constructor中使用this.props的时候,super需要加入(props),
此时用props也行,用this.props也行,他俩都是一个东西。(不过props可以是任意参数,this.props是固定写法)。
如图:
![](https://img.haomeiwen.com/i12442612/c8db434745b7b9d1.png)
** 如果在custructor生命周期不使用 this.props或者props时候,可以不传入props**。
下面是一个使用props的场景,此时别忘了 componentWillReceiveProps 生命周期哟。
参考另一篇文章 react的生命周期需要知道的
![](https://img.haomeiwen.com/i12442612/b7f5160b041b959b.png)
接上:如果constructor中不通过super来接收props,在其他生命周期,
诸如componentWillMount、componentDidMount、render中能直接使用this.props吗??
结论:可以的,react在除了constructor之外的生命周期已经传入了this.props了,完全不受super(props)的影响。
所以super中的props是否接收,只能影响constructor生命周期能否使用this.props,其他的生命周期已默认存在this.props
网友评论