React中constructor(props){}究竟是什麼
在React Class中設定state的初始值或者繫結事件時
為什麼需要在 constructor(){} 中加上 super() 呢
我們嘗試去掉 super() 看看編譯的結果:
-
constructor() {
-
this.state = {searchStr: ''};
-
this.handleChange = this.handleChange.bind(this);
-
}
執行這段程式碼時,會發現編譯錯誤:
提示沒有在this之前加上super()
其實就是少了super(),導致了this的 Reference Error
-
class MyComponent extends React.Component {
-
constructor() {
-
console.log(this); // Reference Error
-
}
-
render() {
-
return <div>Hello {this.props.name}</div>;
-
}
-
}
super關鍵字,它指代父類的例項(即父類的this物件)。子類必須在constructor方法中呼叫super方法,否則新建例項時會報錯。這是因為子類沒有自己的this物件,而是繼承父類的this物件,然後對其進行加工。如果不呼叫super方法,子類就得不到this物件。
正確的姿勢應該是這樣
-
constructor() {
-
super();
-
this.state = {searchStr: ''};
-
this.handleChange = this.handleChange.bind(this);
-
}
React的官方例子中都是加上了 props 作為引數
-
constructor(props) {
-
super(props);
-
this.state = {searchStr: ''};
-
this.handleChange = this.handleChange.bind(this);
-
}
那它們的區別在哪兒呢
What's the difference between “super()” and “super(props)” in React when using es6 classes?
借用下stackoverflow上的解釋
There is only one reason when one needs to pass props
to super()
:
When you want to access this.props
in constructor.
(Which is probably redundant since you already have a reference to it.)
意思是說
只有一個理由需要傳遞props作為super()的引數,那就是你需要在建構函式內使用this.props
那官方提供學習的例子中都是寫成super(props),所以說寫成super(props)是完全沒問題的,也建議就直接這樣寫