使用es6类时,React中的“super()”和“super(props)”有什么区别?
何时将props传递给super()是重要的,为什么? 
 class MyComponent extends React.Component { constructor(props) { super(); // or super(props) ? } } 
	
 当需要将props传递给super()时,只有一个原因: 
  当你想在构造函数中访问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 没有影响 。 这是render , shouldComponentUpdate或事件处理程序总是有权访问它。 
Ben Alpert在一个类似问题的答案中明确地说过。
文档 – 状态和生命周期,将本地状态添加到类,第2点 -推荐:
类组件应该总是使用
props调用基础构造器。
但是,没有提供任何理由。 我们可以推测这是因为子类或未来的兼容性。
(感谢@MattBrowne的链接)
 在这个例子中,你正在扩展React.Component类,并且根据ES2015规范,一个子类的构造函数在调用super()之前不能使用this 。 另外,ES2015类构造函数如果是子类,则必须调用super() 。 
 class MyComponent extends React.Component { constructor() { console.log(this); // Reference Error } render() { return <div>Hello {this.props.name}</div>; } } 
相比之下:
 class MyComponent extends React.Component { constructor() { super(); console.log(this); // this logged to console } render() { return <div>Hello {this.props.name}</div>; } } 
这个优秀的堆栈溢出答案更详细
 您可能会看到通过扩展React.Component类创build的组件的示例,但不会调用super()但您会注意到这些组件没有constructor ,因此为什么没有必要。 
 class MyOtherComponent extends React.Component { render() { return <div>Hi {this.props.name}</div>; } } 
 从我曾经讲过的一些开发人员的angular度来看,我曾经看到一个混淆之处,那就是没有constructor的组件,因此不会在任何地方调用super() , render()方法仍然可以使用this.props 。 请记住,这个规则和这个需要为constructor创build一个this绑定只适用于constructor 。 
 当你通过props super , this道具得到分配。 看看下面的情况: 
 constructor(props) { super(); console.log(this.props) //undefined } 
你怎么做?
 constructor(props) { super(props); console.log(this.props) //props will get logged. } 
根据源代码
 function ReactComponent(props, context) { this.props = props; this.context = context; } 
 每次有道具时必须通过props而不是手动将它们放入this.props 。 
 这是我做的小提琴: https : //jsfiddle.net/beshanoe/zpxbLw4j/1/ 。 它显示道具默认情况下不在构造函数中。 据我所知他们在方法React.createElement 。 因此,只有在超类的构造函数手动地将prop属性赋值给this.props时才应该调用super(props) 。 如果你只是扩展React.Component调用super(props)将不会和道具做任何事情。 也许它会在React的下一个版本中被改变。 
  super()用于调用父构造函数。 
  super(props)将props传递给父构造函数。 
 在你的例子中, super(props)会调用传递props的React.Component构造函数作为参数。 
 有关super更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super