安裝React Dev Tool
Context對象.displayName
-
使用別名
-
不使用別名
React.createContext
- 創建指定的Context對象
- 組件會找離自己最近的Provider,獲取其value
- 變量名都叫value的情況,就近取AContext
- 變量名有所區分,兩個value都可以獲取
- 可以多組Consumer同時使用
Context.Provider
- Context.Provider是通過React.createContext創建出的上下文對象里的一個組件,組件里可以插入其他組件(其他組件訂閱了這個Context)
- 通過Provider的value屬性將數據傳遞給Consumer組件
- value變化,插入Provider的組件都會重新渲染
- value新舊值的對比算法和
Object.is
相同MDN相等性判斷
- 不用<Context.Provider>包裹,則匹配不到Provider,則使用默認值(其他情況均不使用默認參數)
- 注意,用Provider包裹,但不提供value值/或提供undefined,則子組件獲取到的是undefined,不會使用默認值
// 在對數學有要求的業務中,如溫度的判斷,+0 -0應不同,可區分
Object.is(-0, +0) // false
Object.is(NaN, NaN) // true
Context.Consumer
- 訂閱Context的變更
- Consumer內部使用函數作為子元素 → function as a child(有一類組件,內部使用函數作為子元素)
- 函數接收離Context最近的Provider提供的value
- 沒有Provider則取defaultValue
contextType
- 正確寫法
static contextType = CityContext
- 賦值的一定是由
React.createContext()
創建出的Context對象 static contextType
對于contextType不賦值會報錯,static a
普通屬性不賦值則不會報錯- 是靜態屬性,用ES3的寫法是
Selector.contextType = CityContext
- 不管是否指定contextType ,this.context都存在,只是
{}
和有內容的區別 - 指定contextType即給當前環境下的Context重新指定引用
- this.context → CityContext
- 在生命周期函數和render函數中都可以訪問
- Provider、Consumer組件比contextType 語義化更好