我见过许多代码片段,例如HelloWorld
,其中props
传递给super()
。当在构造函数中没有访问this.props
时,这样做的原因是什么?
class HelloWorld extends Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
this.logMessage = this.logMessage.bind(this);
}
logMessage() {
console.log(this.state.message);
}
render() {
return (
<input type="button" value="Log" onClick={this.logMessage} />
);
}
}
在安装React组件之前,会调用它的构造函数。在实现React组件子类的构造函数时,应该在任何其他语句之前调用super(props)
。否则,this.props
将在构造函数中未定义,这可能导致错误。
阅读Here了解更多详情。
如果您不打算在构造函数中使用this.props
,则不必像以下那样将它放入super()
:
constructor(){
super();
this.state = { randomState: "" };
this.randomProperty = null;
}
但是,在某些情况下,可以在构造函数中访问并使用从父组件传递的props
来初始化状态(这些props不受prop更改影响)。通过将props
传递给super
,您现在可以在构造函数中使用this.props
。
constructor(props){
super(props);
this.state = { randomVar: props.initialValue, propDependentState: this.props.someValue };
this.someVar = props.defaultValue;
this.anotherVar = this.props.openToChangesProp;
}
请注意,直接传递给此组件的那些props
是构造函数可访问的唯一道具。使用redux props
从状态映射的connect
包含在此处无法访问的道具中,因为该组件尚未安装。
你不必做super(props)
。这样做只是为了访问构造函数中的props
。你可以写:
constructor(){
super()
this.state={}
}
如果你没有通过super(props)
:
constructor(props){
super()
console.log('this.props', this.props); // => undefined
console.log('props', props); // => whatever the props is
}