當咱們在寫React時候 會用到ES6中的class語法 ,比較常見的狀況以下:javascript
class MyClass extends React.Component{ constructor(){ super() } }
這裏有兩個問題:java
是否有必要在constructor
中調用super()
函數?react
調用super()
和super(props)
有何區別 ?es6
解答 Q1:ide
Always call super() if you have a constructor and don't worry about it if you don't have a constructor函數
只有當你有一個constructor
時候調用super()纔是必須的 看代碼:post
class MyClass extends React.component{ render(){ return <div>Hello {this.props.world}</div> } }
上述代碼徹底符合規定因此你其實並無必要去爲你建立的每一個React Component 調用super()
話分兩頭 若是你的代碼中有constructor
你就必須調用super()
this
class MyClass extends React.component { constructor(){ console.log(this) //Error: 'this' is not allowed before super() } }
出現上述錯誤的緣由是 super()
未被調用以前 this
還未被初始化 (uninitialized) 瞭解更多
或許聰敏的你會想着 使用一個空的constructor
從而擺脫super()
code
class MyClass extends React.component { constructor(){} // Error: missing super() call in constructor }
ES6的 class
的constructors若是屬於子類就 必須調用super()
方法 因此一旦你的代碼有 constructor
你就必須調用用 super()
component
解答Q 2:
Call super(props) only if you want to access this.props inside the constructor. React automatically set it for you if you want to access it anywhere else.
假使你想獲取到constructor
中的this.props
你就必須調用super(props)
而後React就會自動爲你自動爲你配置好它 以便你能夠在隨便什麼地方調用它
看一下使用super()
和 super(props)
的不一樣 :
class MyClass extends React.component{ constructor(props){ super(); console.log(this.props); // this.props is undefined } }
當使用super(props)
時 你能夠從constructor
中獲取到this.props
class MyClass extends React.component{ constructor(props){ super(props); console.log(this.props); // prints out whatever is inside props } }
固然還有一點 當你想在其餘地方使用它時 也沒有必要將props傳遞到constructor中 React會自動爲你設置好它 瞭解更多
class MyClass extends React.component{ render(){ // There is no need to call `super(props)` or even having a constructor // this.props is automatically set for you by React // not just in render but another where else other than the constructor console.log(this.props); // it works! } }
個人理解是 總之 須要綁定 this.
方法或是須要在 constructor 使用操做 props 定義 state,就須要 constructor ,不然 例如在其餘方法中(如 render()
)使用 this.props 則不必要使用 constructor