ReactJS 构造函数“this”未定义错误

Shu*_*ham 1 javascript reactjs

我在构造函数中遇到未定义的错误。让我知道这背后的原因是什么。我从源代码中读到,要么编译器自动创建构造函数并可用此引用,要么需要手动添加带有 super() 作为第一个语句的构造函数。

class A extends Component {
  constructor() {
    // this undefined error
    console.log('construtor');
    this.state = {name: ''}        
  }
}
Run Code Online (Sandbox Code Playgroud)

Aka*_*kar 5

之所以不能在 super() 之前允许这样做,是因为如果不调用 super() 则它是未初始化的。然而,即使我们不使用它,我们也需要在构造函数中使用 super(),因为如果 ES6 类构造函数是子类,则它们必须调用 super。因此,只要有构造函数,就必须调用 super()。(但是子类不必有构造函数)。

在 super 中发送 props 不是强制性的。如果你不想使用 this.props 那么你可以简单地调用 super() 。

class A extends React.Component {   
    constructor(props) {
    super(props);
    console.log('construtor');
    this.state = {name: ''}           
    } 
}
Run Code Online (Sandbox Code Playgroud)