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.
应该在此之前调用超类的构造函数,以便在子类开始配置之前完成此配置.否则超类构造函数可以通过子类修改它.超类不应该知道关于子类的东西.这就是为什么在构造函数中调用super()应该在访问它之前.
原文地址:https://www.jb51.cc/js/150483.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。