当是重要的传球props到super()了,为什么?
props
super()
class MyComponent extends React.Component { constructor(props) { super(); // or super(props) ? } }
只有一种原因需要传递props给super():
当您要this.props在构造函数中访问时。
this.props
通过:
class MyComponent extends React.Component { constructor(props) { super(props) console.log(this.props) // -> { icon: 'home', … } } }
未通过:
class MyComponent extends React.Component { constructor(props) { super() console.log(this.props) // -> undefined // Props parameter is still available console.log(props) // -> { icon: 'home', … } } render() { // No difference outside constructor console.log(this.props) // -> { icon: 'home', … } } }
注意,通过或不通过props,以super有 没有影响 对以后的用途this.props之外constructor。也就是说render,shouldComponentUpdate或事件处理程序 始终 可以访问它。
super
constructor
render
shouldComponentUpdate
这是索菲·阿尔珀特(Sophie Alpert)对类似问题的回答中明确指出的。
建议使用“ 状态和生命周期,将本地状态添加到类,第2点”中的文档:
类组件应始终使用调用基本构造函数props。
但是,没有提供任何理由。我们可以推测它是由于子类化还是出于将来的兼容性。
(感谢@MattBrowne的链接)