日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React?Context源碼實現原理詳解_React

作者:flyzz177 ? 更新時間: 2022-11-22 編程語言

什么是 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

頁面呈現出的效果

打印 ColorContextProviderConsumer

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);newChildrenConsumerchildren 被調用之后的返回值,render 就是 childrennewValue 是從 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?typeofREACT_PROVIDER_TYPE,它帶有一個 _context 屬性,指向的就是 context 本身,也就是自己的兒子有一個屬性指向自己!!!

  context.Provider = {
    ?typeof: REACT_PROVIDER_TYPE,
    _context: context
  };

Consumer?typeofREACT_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 中,有 HooksDispatcherOnMountInDEVHooksDispatcherOnMount,帶 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

欄目分類
最近更新