在不在其中访问props的情况下,在React构造函数中将props传递给super()的原因是什么?

问题描述 投票:5回答:3

我见过许多代码片段,例如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} />
        );
    }
}
javascript reactjs react-native ecmascript-6
3个回答
1
投票

在安装React组件之前,会调用它的构造函数。在实现React组件子类的构造函数时,应该在任何其他语句之前调用super(props)。否则,this.props将在构造函数中未定义,这可能导致错误。

阅读Here了解更多详情。


1
投票

如果您不打算在构造函数中使用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包含在此处无法访问的道具中,因为该组件尚未安装。


0
投票

你不必做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
 }

请参阅this stackoverflow answer

© www.soinside.com 2019 - 2024. All rights reserved.