提问者:小点点

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


什么时候将props传递给super()是重要的,为什么?

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

共1个答案

匿名用户

当需要将道具传递给超级()时,原因只有一个:

当您要访问构造函数中的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', … }
    }
}

请注意,传递或不传递propssuper构造函数之外的this.props的后续使用没有影响。即rendershouldcomponentupdate或事件处理程序始终具有对其的访问权限。

这在索菲·阿尔伯特对一个类似问题的回答中得到了明确的表述。

文档-状态和生命周期,将本地状态添加到类,第2点-建议:

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

但是,没有提供任何理由。我们可以推测这要么是因为子类化,要么是为了将来的兼容性。

(谢谢@MattBrowne的链接)