[英]What is the reason for passing props to super() in a React constructor when props aren't accessed within it?
[英]Constructor(props) and super(props) VS constructor() and super() in React
我知道這個問題被多次提出過,但現在還不清楚。 很多人只是說:
如果要在那里訪問
this.props
,請將props傳遞給構造函數
Oficial doc說類組件應該總是用props調用基礎構造函數。 ,但是如果我們不將props
傳遞給constructor
,我們仍然會有this.props
到處執行構造函數。
同樣從反應源代碼我們可以看到React.Component function ReactComponent(props, context) { this.props = props; this.context = context; }
源代碼function ReactComponent(props, context) { this.props = props; this.context = context; }
function ReactComponent(props, context) { this.props = props; this.context = context; }
但它讓我更加困惑。 應使用兩個參數調用super()
: props
和context
。 但我們調用了我們的超級空,仍然可以訪問兩個this.props
。 根據ECMA文檔, super()
調用父constructor()
,其參數傳遞給super()
。 但我們的super()
是空的。
所以我的問題是:
類組件應始終使用props調用基礎構造函數。
super()
和constructor()
為空,React如何將props
設置為子組件? super()
和constructor()
在子組件中可以訪問道具的React功能的錯誤嗎? 以下是Dan Abramov的回答:
但是如果我們不將
props
傳遞給constructor
,除了constructor
之外,我們仍然會有this.props
。
是的,React在constructor
運行后仍然設置this.props
。 盡管如此,讓這些this.props
在某些地方而不是其他地方工作仍然令人困惑。 特別是如果constructor
和其他方法都調用一些讀取this.props
共享方法。 因此,為了避免任何潛在的混淆,我們建議始終調用super(props)
。
同樣從
Create Element
源代碼中你可以看到createElement
無論你是否使用super(props)
都會添加道具
createElement()
與此問題無關。 它創建一個元素,而不是實例。
因此,回到你的問題,從技術上講,只有你計划在constructor
訪問this.props
或從constructor
調用的任何方法時才有必要。 然而,要記住這一點是非常困惑的。 您可能知道它而不是調用super(props)
,但是團隊中的下一個人將希望在constructor
訪問this.props
並且會感到驚訝它不起作用。 總是指定它以避免這些問題更容易。
如果在反應組件的代碼中沒有定義構造函數,您可以假設它將自動綁定在幕后,例如:
constructor(props){
super(props);
}
一旦你明確定義了一個構造函數,你必須記住總是把那些代碼放在其他地方它將被遺漏...你基本上只是覆蓋一個默認方法:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.