【每日一題】React里的context

人生苦短,總需要一點儀式感。比如學(xué)前端~
Context 有哪些屬性?
createContext創(chuàng)建 Context 對象Provider將 context 的值傳遞給消費組件contextType掛載在組件上,屬性會被賦值為由React.createContext()創(chuàng)建的 Context 對象,可以使用 this.context 來消費最近 Context 上的那個值Consumer訂閱 context 的變更,需要函數(shù)作為子元素displayName作為 context 的屬性,ReactDevTools 使用該字符串來確定 context 要顯示的內(nèi)容
怎么使用 Context 開發(fā)組件?
父組件創(chuàng)建 Context,子組件可以通過指定 contextType 拿到最近父組件的 context 使用生產(chǎn)消費模式的 Provider 包括子組件,子組件通過 props 獲取 context 使用 Consumer, 接收回調(diào)函數(shù),可以拿到 context
除了實例的屬性可以獲得 Context 外,哪些地方還能直接獲取 Context ?
constructor生命周期 : componentWillReceiveProps(nextProps,nextContext)shouldComponentUpdate(nextProps ,nextState,nextContext)componentWillUpdate(nextProps, ,nextState, nextContext)
為什么 React 并不推薦我們優(yōu)先考慮使用 Context?
Context 目前并未完善,會在后面的版本中有很大的變化,為了給升級帶來巨大的影響 Context 會破壞組件樹之間的依賴關(guān)系 Context 的值更新要依賴 setState/useState,這并不可靠,因為中間的組件可能會改變它,導(dǎo)致其他組件不能保證 context 的更新

讓我們一起攜手同走前端路!

● 三欄響應(yīng)式布局(左右固寬中間自適應(yīng))的5種方法
評論
圖片
表情
