javascript - 在构造函数中访问道具的正确方法是什么?
问题描述
在构造函数中访问道具的正确方法是什么?是的,我知道在 React 文档中说
在为 React.Component 子类实现构造函数时,您应该在任何其他语句之前调用 super(props)。否则,this.props 将在构造函数中未定义,这可能会导致错误
this.props
更清楚地说,如果我们可以在构造函数中使用道具,为什么我们需要
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(props)
// -> { something: 'something', … }
// absolutely same
console.log(this.props)
// -> { something: 'something', … }
}
}
在某些情况下何时使用props
over this.props
?
解决方案
this.props
并且props
在构造函数中可以互换,因为this.props === props
只要传递props
给super
. 使用this.props
允许立即检测错误:
constructor() {
super();
this.state = { foo: this.props.foo }; // this.props is undefined
}
一致的使用this.props
使得重构构造函数体变得更容易:
constructor(props) {
super(props);
this.state = { foo: this.props.foo };
}
至
state = { foo: this.props.foo };
只this.
需要删除即可。
在 TypeScript中也存在打字问题props
,这this.props
对于类型化组件来说更可取。
推荐阅读
- python-3.x - 如何使用 tkinter StringVar 使大于或小于
- c# - 如何在运行时使 FlowLayoutPanel 可调整大小?
- python - 为什么我不能覆盖“filedialog.askdirectory”给定目录中的文件?
- dax - 测量平均值
- mongodb - 如何用另一个数组字段的平均值更新 MongoDB 中所有文档中的字段?
- python-3.x - 导入 pandas.io.common 时运行 vispr 会抛出 EmptyDataError
- c - 多平台 C BLE 依赖问题
- typescript - 打字稿制作一个以数组为键,以数组为值的地图
- android - 在 Kotlin 数据类中返回数组或对象
- amazon-web-services - ECS Fargate 在新任务的不同 IP 上启动 - 如何管理它?