小编典典

使用es6类时,React中的“ super()”和“ super(props)”有什么区别?

reactjs

当是重要的传球propssuper()了,为什么?

class MyComponent extends React.Component {
  constructor(props) {
    super(); // or super(props) ?
  }
}

阅读 376

收藏
2020-07-22

共1个答案

小编典典

只有一种原因需要传递propssuper()

当您要this.props在构造函数中访问时。

通过:

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

未通过:

class MyComponent extends React.Component {    
    constructor(props) {
        super()

        console.log(this.props)
        // -> undefined

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

注意,通过或不通过props,以super没有影响
对以后的用途this.props之外constructor。也就是说rendershouldComponentUpdate或事件处理程序
始终 可以访问它。

这是索菲·阿尔珀特(Sophie Alpert)对类似问题的回答中明确指出的。


建议使用“ 状态和生命周期,将本地状态添加到类,第2点”中的文档:

类组件应始终使用调用基本构造函数props

但是,没有提供任何理由。我们可以推测它是由于子类化还是出于将来的兼容性。

(感谢@MattBrowne的链接)

2020-07-22