天天看點

React constructor中的super

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isOn: true };
  }
  // ...
}
           

對于上面的類Checkbox來說,它的super是React.Component

接下來我們依次讨論下列問題:

1.如果不調用super會怎麼樣

2.調用了super但不傳props會怎麼樣

3.沒有constructor時會怎麼樣

一.如果不調用super,那麼constructor中就不能使用this

就像下面的例子

constructor(props){
    this.state = {
      name : '沒調用父級的constructor'
    }
  } 
           

使用了this報錯

React constructor中的super

React這樣做的目的是為了防止,在用到父級的資料時,出現未定義的情況,看下面的例子

class Person {
  constructor(name) {
    this.name = name;
  }
}

class PolitePerson extends Person {
  constructor(name) {
    this.greetColleagues(); 
    super(name);
  }
  greetColleagues() {
    alert('Good morning folks!');
    alert('My name is ' + this.name + ', nice to meet you!');
  }
}
           

上面的例子會發現PolitePerson是Person的子類,在它的constructor中先調用了greetColleagues函數,這個函數中通路了this.name,由于父級還未被初始化,值undefined,是以為了防止出現這種情況,React就規定,隻有在super被調用之後才可以使用this

二.  調用super時不傳props會怎麼樣

看下面代碼

class Button extends React.Component {
  constructor(props) {
    super(); // ? We forgot to pass props
    console.log(props);      // ✅ {}
    console.log(this.props); // ? undefined 
  }
}
           

結果就是this.props的值為undefined,有人可能會說啊,不對呀,我在render或者其它函數裡都可以用啊。确實,那是因為React為我們幹了一件事情

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}
           

在constructor執行完之後,React幫你在執行個體上添加了props屬性,指派為props,以至于這是可以通路props,如果在super調用時沒有傳props的話,那麼在constructor裡用this.props是通路不到props的值的,因為它自己沒有的東西會去父級中找

是以為了防止出現一些不必要的錯誤,React是建議我們加上props的,盡管沒有硬性的規定

三. 如果class中沒有constructor,React會自動幫我們調用super,并把所有的參數傳過去,是以不用擔心