網站首頁 編程語言 正文
什么是 Context
目前來看 Context 是一個非常強大但是很多時候不會直接使用的 api。大多數項目不會直接使用 createContext
然后向下面傳遞數據,而是采用第三方庫(react-redux)。
想想項目中是不是經常會用到 @connect(...)(Comp)
以及 <Provider value={store}><App /></Provider>
?
Context 提供了一個無需為每層組件手動添加 props,就能在組件樹間進行數據傳遞的方法。
一個頂層數據,想要傳遞到某些深層組件,通過 props
逐層傳遞將會非常繁瑣,使用 Context 可避免顯式地通過組件樹逐層傳遞 props
。
Context 使用示例
import React, { Component, createContext, useConText } from 'react' const ColorContext = createContext(null) const { Provider, Consumer } = ColorContext console.log('ColorContext', ColorContext) console.log('Provider', Provider) console.log('Consumer', Consumer) class App extends Component { constructor(props) { super(props) this.state = { color: 'red', background: 'cyan', } } render() { return <Provider value={this.state}>{this.props.children}</Provider> } } function Article({ children }) { return ( <App> <h1>Context</h1> <p>hello world</p> {children} </App> ) } function Paragraph({ color, background }) { return ( <div style={{ backgroundColor: background }}> <span style={{ color }}>text</span> </div> ) } function TestContext() { return ( <Article> <Consumer>{state => <Paragraph {...state} />}</Consumer> </Article> ) } export default TestContext
頁面呈現出的效果
打印 ColorContext
、Provider
、Consumer
createContext
// createContext 可以讓我們實現狀態管理 // 還能夠解決傳遞 Props drilling 的問題 // 假如一個子組件需要父組件的一個屬性,但是中間間隔了好幾層,這就會出現開發和維護的一個成本。這時候就可以通過這個 API 來解決 function createContext(defaultValue, calculateChangedBits) { var context = { ?typeof: REACT_CONTEXT_TYPE, _calculateChangedBits: calculateChangedBits, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. // 以下兩個屬性是為了適配多平臺 _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null }; // 以下的代碼很簡單,就是在 context 上掛載 Provider 和 Consumer,讓外部去使用 context.Provider = { ?typeof: REACT_PROVIDER_TYPE, _context: context }; var Consumer = { ?typeof: REACT_CONTEXT_TYPE, _context: context, _calculateChangedBits: context._calculateChangedBits }; context.Consumer = Consumer; context._currentRenderer = null; context._currentRenderer2 = null; return context; }
在 react
包里面僅僅是生成了幾個對象,比較簡單,接下來看看它發揮作用的地方。
在 Consumer
children
的匿名函數里面打 debugger。
查看調用棧
主要是 newChildren = render(newValue);
,newChildren
是 Consumer
的 children
被調用之后的返回值,render
就是 children
,newValue
是從 Provider
value
屬性的賦值。
newProps
newValue
接下來看 readContext
的實現
let lastContextDependency: ContextDependency<mixed> | null = null; let currentlyRenderingFiber: Fiber | null = null; // 在 prepareToReadContext 函數 currentlyRenderingFiber = workInProgress; export function readContext<T>( context: ReactContext<T>, observedBits: void | number | boolean, ): T { let contextItem = { context: ((context: any): ReactContext<mixed>), observedBits: resolvedObservedBits, next: null, }; if (lastContextDependency === null) { // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.contextDependencies = { first: contextItem, expirationTime: NoWork, }; } else { // Append a new context item. lastContextDependency = lastContextDependency.next = contextItem; } } // isPrimaryRenderer 為 true,定義的就是 true // 實際就是一直會返回 context._currentValue return isPrimaryRenderer ? context._currentValue : context._currentValue2; }
跳過中間,最后一句 return context._currentValue
,而
就把頂層傳下來的 context
的值取到了
context 為什么從上層可以一直往下面傳這點現在還沒有看懂,后面熟悉跨組件傳遞的實現之后再寫一篇文章解釋,囧。
Context 的設計非常特別
Provider
Consumer
是 context 的兩個屬性。
var context = { ?typeof: REACT_CONTEXT_TYPE, _currentValue: defaultValue, _currentValue2: defaultValue, Provider: null, Consumer: null };
Provider
的 ?typeof
是 REACT_PROVIDER_TYPE
,它帶有一個 _context
屬性,指向的就是 context
本身,也就是自己的兒子有一個屬性指向自己!!!
context.Provider = { ?typeof: REACT_PROVIDER_TYPE, _context: context };
Consumer
的 ?typeof
是 REACT_CONTEXT_TYPE
,它帶也有一個 _context
屬性,也是自己的兒子有一個屬性指向自己!!!
var Consumer = { ?typeof: REACT_CONTEXT_TYPE, _context: context, _calculateChangedBits: context._calculateChangedBits };
所以可以做一個猜想, Provider
的 value 屬性賦予的新值肯定通過 _context
屬性傳到了 context
上,修改了 _currentValue
。同樣,Consumer
也是依據 _context
拿到了 context
的 _currentValue
,然后 render(newValue)
執行 children
函數。
useContext
useContext
是 react hooks 提供的一個功能,可以簡化 context 值得獲取。
下面看使用代碼
import React, { useContext, createContext } from 'react' const NameCtx = createContext({ name: 'yuny' }) function Title() { const { name } = useContext(NameCtx) return <h1># {name}</h1> } function App() { return ( <NameCtx.Provider value={{ name: 'lxfriday' }}> <Title /> </NameCtx.Provider> ) } export default App
我么初始值給的是 {name: 'yuny'}
,實際又重新賦值 {name: 'lxfriday'}
,最終頁面顯示的是 lxfriday
。
useContext 相關源碼
先看看 react 包中導出的 useContext
/** * useContext * @param Context {ReactContext} createContext 返回的結果 * @param unstable_observedBits {number | boolean | void} 計算新老 context 變化相關的,useContext() second argument is reserved for future * @returns {*} 返回的是 context 的值 */ export function useContext<T>( Context: ReactContext<T>, unstable_observedBits: number | boolean | void, ) { const dispatcher = resolveDispatcher(); return dispatcher.useContext(Context, unstable_observedBits); }
// Invalid hook call. Hooks can only be called inside of the body of a function component. function resolveDispatcher() { const dispatcher = ReactCurrentDispatcher.current; return dispatcher; }
/** * Keeps track of the current dispatcher. */ const ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: (null: null | Dispatcher), };
看看 Dispatcher
,都是和 React Hooks 相關的。
再到 react-reconciler/src/ReactFiberHooks.js 中,有 HooksDispatcherOnMountInDEV
和 HooksDispatcherOnMount
,帶 InDEV
的應該是在 development
環境會使用到的,不帶的是在 `production 會使用到。
const HooksDispatcherOnMount: Dispatcher = { readContext, useCallback: mountCallback, useContext: readContext, useEffect: mountEffect, useImperativeHandle: mountImperativeHandle, useLayoutEffect: mountLayoutEffect, useMemo: mountMemo, useReducer: mountReducer, useRef: mountRef, useState: mountState, useDebugValue: mountDebugValue, }; HooksDispatcherOnMountInDEV = { // ... useContext<T>( context: ReactContext<T>, observedBits: void | number | boolean, ): T { return readContext(context, observedBits); }, }
在上面 useContext
經過 readContext
返回了 context 的值,readContext
在上面有源碼介紹。
debugger 查看調用棧
初始的 useContext
在 HooksDispatcherOnMountInDEV
中
readContext
中
經過上面源碼的詳細分析, 大家對 context 的創建和 context 取值應該了解了,context 設計真的非常妙!!
原文鏈接:https://juejin.cn/post/7152744351687245831
相關推薦
- 2022-08-10 python數組中的?k-diff?數對例題解析_python
- 2023-01-07 Android實現簡單的自定義ViewGroup流式布局_Android
- 2022-10-21 解決Git?Revert?再次合代碼無效問題_相關技巧
- 2023-02-02 一文教你利用Python制作一個生日提醒_python
- 2021-12-11 Redis之sql緩存的具體使用_Redis
- 2022-04-20 在Python反編譯中批量pyc轉?py的實現代碼_python
- 2022-10-18 Python中尋找數據異常值的3種方法_python
- 2022-03-28 Python垃圾回收及Linux?Fork_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支