什么时候通过props
到super()
分很重要,为什么?
class MyComponent extends React.Component {
constructor(props) {
super(); // or super(props) ?
}
}
什么时候通过props
到super()
分很重要,为什么?
class MyComponent extends React.Component {
constructor(props) {
super(); // or super(props) ?
}
}
当一个人需要通过props
到super()
级考试时,只有一个原因:
When you want to access 100 in constructor.
经过:
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
都有no effect关于constructor
之外this.props
的后续用法.也就是说,render
、shouldComponentUpdate
或事件处理程序always可以访问它.
这在苏菲·阿尔伯特(Sophie Alpert)的answer篇关于类似问题的文章中有明确的表述.
文件-State and Lifecycle, Adding Local State to a Class, point 2-建议:
类组件应始终使用
props
调用基构造函数.
然而,没有提供任何理由.我们可以推测这要么是因为子类化,要么是为了将来的兼容性.
(感谢@MattBrowne的链接)