什么时候将props
传递给super()
是重要的,为什么?
class MyComponent extends React.Component {
constructor(props) {
super(); // or super(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
的后续使用没有影响。即render
、shouldcomponentupdate
或事件处理程序始终具有对其的访问权限。
这在索菲·阿尔伯特对一个类似问题的回答中得到了明确的表述。
文档-状态和生命周期,将本地状态添加到类,第2点-建议:
类组件应该始终使用props
调用基构造函数。
但是,没有提供任何理由。我们可以推测这要么是因为子类化,要么是为了将来的兼容性。
(谢谢@MattBrowne的链接)