问题描述
什么时候将 props
传递给 super()
很重要,为什么?
When is it important to pass props
to super()
, and why?
class MyComponent extends React.Component {
constructor(props) {
super(); // or super(props) ?
}
}
推荐答案
需要将props
传递给super()
的原因只有一个:
There is only one reason when one needs to pass props
to super()
:
当你想在构造函数中访问 this.props
时.
When you want to access this.props
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
对this.props
的后续使用没有影响构造函数
之外.即 render
、shouldComponentUpdate
或事件处理程序总是可以访问它.
Note that passing or not passing props
to super
has no effect on later uses of this.props
outside constructor
. That is render
, shouldComponentUpdate
, or event handlers always have access to it.
这在 Sophie Alpert 的一位回答类似问题.
This is explicitly said in one Sophie Alpert's answer to a similar question.
文档—状态和生命周期,将本地状态添加到类,第 2 点——推荐:
类组件应始终使用 props
调用基本构造函数.
然而,没有提供任何理由.我们可以推测它要么是因为子类化,要么是为了未来的兼容性.
However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.
(感谢@MattBrowne 提供链接)
(Thanks @MattBrowne for the link)
这篇关于"super()" 和有什么不一样?和“超级(道具)"在 React 中使用 es6 类时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!