2017-09-25 88 views
0

I'getting在構造函數中未定義此錯誤。 讓我知道這是什麼原因。我從源文件中讀取,編譯器會自動創建構造函數並可用此引用,或者需要使用super()作爲第一個語句手動添加構造函數。ReactJS構造函數'this'未定義錯誤

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

回答

3

super()之前不能被允許的原因是因爲如果沒有調用super(),這是未初始化的。但是,即使我們不使用它,我們也需要在構造函數中使用super(),因爲如果ES6類構造函數是子類,它們必須調用超類。因此,只要你有一個構造函數,就必須調用super()。 (但是一個子類不一定有構造函數)。

發送超級道具不是強制性的。如果你不想使用this.props,那麼你可以簡單地調用super()。

class A extends React.Component { 
    constructor(props) { 
    super(props); 
    console.log('construtor'); 
    this.state = {name: ''}   
    } 
} 
1

子類必須在構造函數中具有超級用於初始化目的。如果沒有super(),就不能訪問'this'。

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