gpt4 book ai didi

javascript - 在构造函数中访问 Prop 的正确方法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:02 24 4
gpt4 key购买 nike

在构造函数中访问 props 的正确方法是什么?是的,我知道在 React 文档中是这样说的

When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs

更清楚的是,如果我们可以在构造函数中使用 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 而不是 this.props

最佳答案

this.propsprops 在构造函数中可以互换,因为 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. 需要删除。

还有typing problems with props in TypeScript ,这使得 this.props 更适合类型化组件。

关于javascript - 在构造函数中访问 Prop 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53003908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com