Nor*_*yan 3 javascript constructor class ecmascript-6 reactjs
在构造函数中访问props的正确方法是什么?是的,我知道在React文档中说
在为React.Component子类实现构造函数时,应在其他任何语句之前调用super(props)。否则,this.props将在构造函数中未定义,这可能会导致错误
更明确地说,this.props如果仅在构造函数中使用props ,为什么会需要
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(props)
// -> { something: 'something', … }
// absolutely same
console.log(this.props)
// -> { something: 'something', … }
}
}
Run Code Online (Sandbox Code Playgroud)
有什么情况下可以使用props完this.props吗?
this.props并且props因为是在构造函数中互换this.props === props,只要props被传递到super。使用的this.props允许立即发现错误:
constructor() {
super();
this.state = { foo: this.props.foo }; // this.props is undefined
}
Run Code Online (Sandbox Code Playgroud)
一致的使用this.props使重构构造函数主体更容易:
constructor(props) {
super(props);
this.state = { foo: this.props.foo };
}
Run Code Online (Sandbox Code Playgroud)
至
state = { foo: this.props.foo };
Run Code Online (Sandbox Code Playgroud)
只this.需要删除。
TypeScript中还存在键入问题props,这使this.props键入组件更可取。
此建议的存在是为了防止您通过从构造函数调用对象上的其他方法(依赖于this.props. 您不想显式地将 props 传递给这些。
例如,以下内容将是一个错误,因为您doStuff之前调用过super
class MyComponent extends React.Component {
constructor(props) {
this.doStuff()
super(props)
}
doStuff() {
console.log("something is: " + this.props.something)
}
}
Run Code Online (Sandbox Code Playgroud)