美文网首页
知识点小记:🌟🌟🌟🌟🌟constructor中的super

知识点小记:🌟🌟🌟🌟🌟constructor中的super

作者: 达摩会武术 | 来源:发表于2019-05-30 14:43 被阅读0次

(本文摘抄)
有的小伙伴每次写组件都会习惯性在constructor和super中写上props,那么这个是必要的吗??

如图: image

首先要明确很重要的一点就是:

可以不写constructor,一旦写了constructor,就必须在此函数中写super(),

此时组件才有自己的this,在组件的全局中都可以使用this关键字,

否则如果只是constructor 而不执行 super() 那么以后的this都是错的!!!

来源ES6 : http://es6.ruanyifeng.com/#docs/class-extends

image

但是super中必须写参数props吗?? 答案是不一定,先看代码:

有props:

image image

无props:

image image

可以得出结论:****当想在constructor中使用this.props的时候,super需要加入(props),

此时用props也行,用this.props也行,他俩都是一个东西。(不过props可以是任意参数,this.props是固定写法)

如图:

image

** 如果在custructor生命周期不使用 this.props或者props时候,可以不传入props**。

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

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

image

接上:如果constructor中不通过super来接收props,在其他生命周期,

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

结论:可以的,react在除了constructor之外的生命周期已经传入了this.props了,完全不受super(props)的影响

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

相关文章

网友评论

      本文标题:知识点小记:🌟🌟🌟🌟🌟constructor中的super

      本文链接:https://www.haomeiwen.com/subject/hcqvtctx.html