class MyComponent extends React.Component { constructor(props) { super(props); this.state = { /* initial state */ }; } }
解决方法
The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name “constructor” in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of a parent class.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
这意味着如果你的类MyComponent扩展了React.Component,你总是需要调用super()来定义它.
If you don’t specify a constructor method,a default constructor is used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor#Default_constructors
应该在此之前调用超类的构造函数,以便在子类开始配置之前完成此配置.否则超类构造函数可以通过子类修改它.超类不应该知道关于子类的东西.这就是为什么在构造函数中调用super()应该在访问它之前.