【问题标题】:What is the reason for passing props to super() in a React constructor when props aren't accessed within it?当在 React 构造函数中没有访问 props 时,将 props 传递给 super() 的原因是什么?
【发布时间】:2019-02-09 00:13:07
【问题描述】:

我见过很多代码 sn-ps,例如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} />
        );
    }
}

【问题讨论】:

  • 真的没有理由。如果你没有在构造函数中使用this.props,你需要做的就是调用super()Component 超类可以很好地设置 props,只是在构造函数中无法访问它们。

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

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

阅读Here了解更多详情。

【讨论】:

    【解决方案2】:

    如果您不打算在构造函数中使用this.props,则不必像这样将其放入super()

    constructor(){
       super();
       this.state = { randomState: "" };
       this.randomProperty = null;
    }
    

    但是,在某些情况下,从父组件传递的props 可以被访问并在构造函数内部用于初始化状态(这些道具不受道具更改的影响)。通过将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 是构造函数可以访问的唯一道具。 props 使用 redux 从状态映射 connect 包含在 props 中,由于组件尚未安装,因此无法在此处访问。

    【讨论】:

      【解决方案3】:

      您不必执行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

      【讨论】:

        猜你喜欢
        • 2018-05-06
        • 2016-11-26
        • 2016-10-19
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        • 2017-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多