• react context 源码解读


    源码地址

    注: 这里,为了读起来思路更清晰一些,我们将__DEV__的代码去掉。

    import {REACT_PROVIDER_TYPE, REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
    
    import type {ReactContext} from 'shared/ReactTypes';
    
    export function createContext<T>(
      defaultValue: T,
      calculateChangedBits: ?(a: T, b: T) => number,
    ): ReactContext<T> {
      if (calculateChangedBits === undefined) {
        calculateChangedBits = null;
      }
    
      const context: ReactContext<T> = {
        $$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: any),
        Consumer: (null: any),
      };
    
      context.Provider = {
        $$typeof: REACT_PROVIDER_TYPE,
        _context: context,
      };
    
       context.Consumer = context;
    
      return context;
    }

    全局创建的context实例,对外提供Provider和Consumer两个属性,Provider的_context属性值又指向context实例本身,即:当改变Provider组件value的值,会作用到Provider内部的_context属性,进而更新context的_currentValue. 而

    context.Consumer = context

    所以会触发consumer的更新。

     

    参考:https://xie.infoq.cn/article/d56577c78e76508722e37025f

  • 相关阅读:
    如何将一个PDF文件里的图片批量导出
    (二十二)golang--时间和日期相关函数
    (二十一)golang--字符串中的函数
    (二十)golang--变量的作用域
    (十九)golang--函数参数的传递方式
    (十八)golang--defer关键字
    (十七)golang--闭包(简单明了)
    (十六)golang--匿名函数
    (十五)golang--init函数
    【自然语言处理】双语数据预处理
  • 原文地址:https://www.cnblogs.com/ceceliahappycoding/p/14365804.html
Copyright © 2020-2023  润新知