constructor( )
在React中constructor表示父類的構(gòu)造方法,用來(lái)新建父類的this對(duì)象,這是ES6對(duì)類的默認(rèn)方法,該方法是類中必須有的,如果沒(méi)有顯示定義,則會(huì)默認(rèn)添加空的constructor( )方法。
class Point {
}
// 相當(dāng)于
class Point {
constructor() {}
}
super( )
在class方法中,繼承使用 extends 關(guān)鍵字來(lái)實(shí)現(xiàn)。子類 必須 在 constructor( )調(diào)用 super( )方法,否則新建實(shí)例時(shí)會(huì)報(bào)錯(cuò),因?yàn)樽宇悰](méi)有自己的this對(duì)象,而是繼承父類的this對(duì)象,然后對(duì)其進(jìn)行加工,如果不調(diào)用super方法;子類就得不到this對(duì)象。
有super時(shí):

無(wú)
super時(shí):
很明顯自動(dòng)就報(bào)錯(cuò)了,所以只要有
constructor就必須有super
super or super(props)
先看個(gè)例子:
class Main extends React.Component {
constructor() {
super();
this.state = {count: 1};
}
render() {
return (
<div>
{this.state.count}
<App count={this.state.count}/>
</div>
);
}
}
class App extends React.Component {
constructor() { //沒(méi)有寫props
super();
}
render() {
return (
<div>
{this.props.count}
</div>
);
}
}
運(yùn)行后顯示正確,當(dāng)在constructor和super中寫了props,也毫無(wú)影響,運(yùn)行顯示正確,那么將App組件中的constructor改為:
constructor() {
super();
this.state = {c: this.props.count};
}
顯示部分改為:
<div>
{this.state.c}
</div>
那么報(bào)錯(cuò)如下:

當(dāng)把
App組件中的constructor改為:
constructor(props) {
super(props);
this.state = {c: this.props.count};
}
那么運(yùn)行顯示正確
所以說(shuō)super()和super(props)的區(qū)別就是你是否需要在構(gòu)造函數(shù)內(nèi)使用this.props,如果需要那么你就必須要寫props,如果不需要,那么寫不寫效果是一樣的