使用es6的class定義react組件時(shí),經(jīng)常會(huì)看到下面的代碼:
constructor(props) {
super(props);
...
}
通常會(huì)有兩個(gè)疑問:
- 必須要調(diào)用super()嗎?
- super()與super(props)有什么不同?
一、第一個(gè)問題
先說結(jié)論:
只要存在constructor就要調(diào)用super()
但是,不是每個(gè)react組件都需要constructor,比如下面的代碼是可以正常運(yùn)行的:
class App extends React.Component {
render() {
return (
<h1>{this.props.text}</h1>
);
}
}
很多時(shí)候需要在constructor中訪問this:
constructor() {
console.log(this); --- Syntax error: 'this' is not allowed before super()
}
這是因?yàn)楫?dāng)沒有調(diào)用super()時(shí),this還沒有被初始化,所以不能使用;那如果我不使用this呢?
constructor() {
--- Syntax error: missing super() call in constructor
}
es6會(huì)在語法層面強(qiáng)制你調(diào)用super(),所以得到的結(jié)論就是:<b>只要存在constructor就必須調(diào)用super()</b>
二、第二個(gè)問題
第一個(gè)問題已經(jīng)回答了什么時(shí)候調(diào)用super(),那什么時(shí)候必須要調(diào)用super(props)呢?先說結(jié)論:
當(dāng)需要在constructor中訪問<b>this.props</b>的情況下
從上面的代碼可以看出,即使沒有constructor,依然可以在render中使用this.props,這是因?yàn)閞eact在初始化class后,會(huì)將props自動(dòng)設(shè)置到this中,所以在任何地方都可以直接訪問this.props,除了一個(gè)地方:<b>constructor</b>
constructor(props) {
super();
console.log(this.props); --- undefined
}
所以當(dāng)你需要在constructor中訪問this.props時(shí),才需要設(shè)置super(props)