一文帮你理解PReact10.5.13源码


Posted in Javascript onApril 03, 2021

React源码看过几次,每次都没有坚持下来,索性学习一下PReact部分,网上讲解源码的不少,但是基本已经过时,所以自己来梳理下

render.js部分

import { EMPTY_OBJ, EMPTY_ARR } from './constants';
import { commitRoot, diff } from './diff/index';
import { createElement, Fragment } from './create-element';
import options from './options';

/**
 * Render a Preact virtual node into a DOM element
 * @param {import('./internal').ComponentChild} vnode The virtual node to render
 * @param {import('./internal').PreactElement} parentDom The DOM element to
 * render into
 * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an
 * existing DOM tree rooted at `replaceNode`
 */
export function render(vnode, parentDom, replaceNode) {
 if (options._root) options._root(vnode, parentDom);

 // We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in
 // hydration mode or not by passing the `hydrate` function instead of a DOM
 // element..
 let isHydrating = typeof replaceNode === 'function';

 // To be able to support calling `render()` multiple times on the same
 // DOM node, we need to obtain a reference to the previous tree. We do
 // this by assigning a new `_children` property to DOM nodes which points
 // to the last rendered tree. By default this property is not present, which
 // means that we are mounting a new tree for the first time.
  // 为了支持多次在一个dom节点上调用render函数,需要在dom节点上添加一个饮用,用来获取指向上一次渲染的虚拟dom树。
  // 这个属性默认是指向空的,也意味着我们第一次正在装备一颗新的树
  // 所以开始时这里的oldVNode是空(不论isHydrating的值),但是如果重复在这个节点上调用render那oldVNode是有值的
 let oldVNode = isHydrating
  ? null
  : (replaceNode && replaceNode._children) || parentDom._children;

 // 用Fragment包裹一下vnode,同时给replaceNode和parentDom的_children赋值
  vnode = (
  (!isHydrating && replaceNode) ||
  parentDom
 )._children = createElement(Fragment, null, [vnode]);

 // List of effects that need to be called after diffing.
  // 用来放置diff之后需要进行各种生命周期处理的Component,比如cdm、cdu;componentWillUnmount在diffChildren的unmount函数中执行不在commitRoot时执行
 let commitQueue = [];
 diff(
  parentDom, // 这个使用parentDom的_children属性已经指向[vnode]了
  // Determine the new vnode tree and store it on the DOM element on
  // our custom `_children` property.
  vnode,
  oldVNode || EMPTY_OBJ, // 旧的树
  EMPTY_OBJ,
  parentDom.ownerSVGElement !== undefined,
    // excessDomChildren,这个参数用来做dom复用的作用
  !isHydrating && replaceNode
   ? [replaceNode]
   : oldVNode
   ? null
   : parentDom.firstChild // 如果parentDom有子节点就会把整个子节点作为待复用的节点使用
   ? EMPTY_ARR.slice.call(parentDom.childNodes)
   : null,
  commitQueue,
    // oldDom,在后续方法中用来做标记插入位置使用
  !isHydrating && replaceNode
   ? replaceNode
   : oldVNode
   ? oldVNode._dom
   : parentDom.firstChild,
  isHydrating
 );

 // Flush all queued effects
  // 调用所有commitQueue中的节点_renderCallbacks中的方法
 commitRoot(commitQueue, vnode);
}

/**
 * Update an existing DOM element with data from a Preact virtual node
 * @param {import('./internal').ComponentChild} vnode The virtual node to render
 * @param {import('./internal').PreactElement} parentDom The DOM element to
 * update
 */
export function hydrate(vnode, parentDom) {
 render(vnode, parentDom, hydrate);
}

create-context.js部分

Context的使用:

Provider的props中有value属性

Consumer中直接获取传值

import { createContext, h, render } from 'preact';

const FontContext = createContext(20);

function Child() {
 return <FontContext.Consumer>
 {fontSize=><div style={{fontSize:fontSize}}>child</div>}
 </FontContext.Consumer>
}
function App(){
 return <Child/>
}
render(
 <FontContext.Provider value={26}>
 <App/>
 </FontContext.Provider>,
 document.getElementById('app')
);

看一下源码:

import { enqueueRender } from './component';

export let i = 0;

export function createContext(defaultValue, contextId) {
 contextId = '__cC' + i++; // 生成一个唯一ID

 const context = {
  _id: contextId,
  _defaultValue: defaultValue,
  /** @type {import('./internal').FunctionComponent} */
  Consumer(props, contextValue) {
   // return props.children(
   //  context[contextId] ? context[contextId].props.value : defaultValue
   // );
   return props.children(contextValue);
  },
  /** @type {import('./internal').FunctionComponent} */
  Provider(props) {
   if (!this.getChildContext) { // 第一次调用时进行一些初始化操作
    let subs = [];
    let ctx = {};
    ctx[contextId] = this;
       
       // 在diff操作用,如果判断一个组件在Comsumer中,会调用sub进行订阅;
       // 同时这个节点后续所有diff的地方都会带上这个context,调用sub方法进行调用
       // context具有层级优先级,组件会先加入最近的context中
    this.getChildContext = () => ctx; 

    this.shouldComponentUpdate = function(_props) {
     if (this.props.value !== _props.value) {
      // I think the forced value propagation here was only needed when `options.debounceRendering` was being bypassed:
      // https://github.com/preactjs/preact/commit/4d339fb803bea09e9f198abf38ca1bf8ea4b7771#diff-54682ce380935a717e41b8bfc54737f6R358
      // In those cases though, even with the value corrected, we're double-rendering all nodes.
      // It might be better to just tell folks not to use force-sync mode.
      // Currently, using `useContext()` in a class component will overwrite its `this.context` value.
      // subs.some(c => {
      //  c.context = _props.value;
      //  enqueueRender(c);
      // });

      // subs.some(c => {
      //  c.context[contextId] = _props.value;
      //  enqueueRender(c);
      // });
            // enqueueRender最终会进入renderComponent函数,进行diff、commitRoot、updateParentDomPointers等操作
      subs.some(enqueueRender);
     }
    };

    this.sub = c => {
     subs.push(c);// 进入订阅数组,
     let old = c.componentWillUnmount;
     c.componentWillUnmount = () => { // 重写componentWillUnmount
      subs.splice(subs.indexOf(c), 1);
      if (old) old.call(c);
     };
    };
   }

   return props.children;
  }
 };

 // Devtools needs access to the context object when it
 // encounters a Provider. This is necessary to support
 // setting `displayName` on the context object instead
 // of on the component itself. See:
 // https://reactjs.org/docs/context.html#contextdisplayname
 // createContext最终返回的是一个context对象,带着Provider和Consumer两个函数
 // 同时Consumber函数的contextType和Provider函数的_contextRef属性都指向context
 return (context.Provider._contextRef = context.Consumer.contextType = context);
}

所以对于Provider组件,在渲染时会判断有没有getChildContext方法,如果有的话调用得到globalContext并一直向下传递下去

if (c.getChildContext != null) {
    globalContext = assign(assign({}, globalContext), c.getChildContext());
   }

   if (!isNew && c.getSnapshotBeforeUpdate != null) {
    snapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);
   }

   let isTopLevelFragment =
    tmp != null && tmp.type === Fragment && tmp.key == null;
   let renderResult = isTopLevelFragment ? tmp.props.children : tmp;

   diffChildren(
    parentDom,
    Array.isArray(renderResult) ? renderResult : [renderResult],
    newVNode,
    oldVNode,
    globalContext,
    isSvg,
    excessDomChildren,
    commitQueue,
    oldDom,
    isHydrating
   );

当渲染遇到Consumer时,即遇到contextType属性,先从Context中拿到provider,然后拿到provider的props的value值,作为组件要获取的上下文信息。同时这时候会调用provider的sub方法,进行订阅,当调用到Provider的shouldComponentUpdate中发现value发生变化时就会将所有的订阅者进入enqueueRender函数。

一文帮你理解PReact10.5.13源码

所以源码中,globalContext对象的每一个key指向一个Context.Provider;componentContext代表组件所在的Consumer传递的上下文信息即配对的Provider的props的value;

同时Provider的shouldComponentUpdate方法中用到了 ·this.props.value !== _props.value· 那么这里的this.props是哪来的?Provider中并没有相关属性。

主要是下面这个地方,当判断没有render方法时,会先用Compoent来实例化一个对象,并将render方法设置为doRender,并将constructor指向newType(当前函数),在doRender中调用this.constructor方法

// Instantiate the new component
    if ('prototype' in newType && newType.prototype.render) {
     // @ts-ignore The check above verifies that newType is suppose to be constructed
     newVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap
    } else {
     // @ts-ignore Trust me, Component implements the interface we want
     newVNode._component = c = new Component(newProps, componentContext);
     c.constructor = newType;
     c.render = doRender;
    }
/** The `.render()` method for a PFC backing instance. */
function doRender(props, state, context) {
 return this.constructor(props, context);
}

diff部分

diff部分比较复杂,整体整理了一张大图

一文帮你理解PReact10.5.13源码

真是不得不吐槽,博客园的编辑器bug太多了,尤其是mac上使用,比如第二次上传代码提交不了;赋值粘贴用不了。。。

只有情怀让我继续在这里更新

到此这篇关于一文帮你理解PReact10.5.13源码的文章就介绍到这了,更多相关PReact10.5.13源码内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Javascript 相关文章推荐
jquery与js函数冲突的两种解决方法
Sep 09 Javascript
JQuery加载图片自适应固定大小的DIV
Sep 12 Javascript
JS清空多文本框、文本域示例代码
Feb 24 Javascript
jQuery select表单提交省市区城市三级联动核心代码
Jun 09 Javascript
javascript实现在某个元素上阻止鼠标右键事件的方法和实例
Aug 12 Javascript
js精准的倒计时函数分享
Jun 29 Javascript
jquery实现静态搜索功能(可输入搜索文字)
Mar 28 jQuery
利用jquery去掉时光轴头尾部线条的方法实例
Jun 16 jQuery
浅谈JavaScript find 方法不支持IE的问题
Sep 28 Javascript
简单说说如何使用vue-router插件的方法
Apr 08 Javascript
element-ui上传一张图片后隐藏上传按钮功能
May 22 Javascript
js实现3D旋转效果
Aug 18 Javascript
JS一分钟在github+Jekyll的博客中添加访问量功能的实现
给原生html中添加水印遮罩层的实现示例
html实现随机点名器的示例代码
如何利用JavaScript实现二叉搜索树
(开源)微信小程序+mqtt,esp8266温湿度读取
Javascript中的解构赋值语法详解
Apr 02 #Javascript
Ajax实现局部刷新的方法实例
You might like
php计算到指定日期还有多少天的方法
2015/04/14 PHP
PHP简单装饰器模式实现与用法示例
2017/06/22 PHP
PHP实现非阻塞模式的方法分析
2018/07/26 PHP
JQuery下关于$.Ready()的分析
2009/12/13 Javascript
Javascript类库的顶层对象名用户体验分析
2010/10/24 Javascript
jQuery插件简单实现方法
2015/07/18 Javascript
数据分析软件之FineReport教程:[5]参数界面JS(全)
2015/08/13 Javascript
每天一篇javascript学习小结(Boolean对象)
2015/11/12 Javascript
jQuery绑定自定义事件的魔法升级版
2016/06/30 Javascript
jQuery快速高效制作网页交互特效
2017/02/24 Javascript
html+javascript+bootstrap实现层级多选框全层全选和多选功能
2017/03/09 Javascript
微信小程序之swiper滑动面板用法示例
2018/12/04 Javascript
vue单文件组件lint error自动fix与styleLint报错自动fix详解
2019/01/08 Javascript
javascript面向对象三大特征之多态实例详解
2019/07/24 Javascript
vue 使用高德地图vue-amap组件过程解析
2019/09/07 Javascript
Angular6项目打包优化的实现方法
2019/12/15 Javascript
antd配置config-overrides.js文件的操作
2020/10/31 Javascript
[02:17]2016完美“圣”典风云人物:Sccc专访
2016/12/03 DOTA
python实现自动网页截图并裁剪图片
2018/07/30 Python
不知道这5种下划线的含义,你就不算真的会Python!
2018/10/09 Python
TensorFlow卷积神经网络之使用训练好的模型识别猫狗图片
2019/03/14 Python
基于pytorch的保存和加载模型参数的方法
2019/08/17 Python
python numpy 常用随机数的产生方法的实现
2019/08/21 Python
解决paramiko执行命令超时的问题
2020/04/16 Python
升级keras解决load_weights()中的未定义skip_mismatch关键字问题
2020/06/12 Python
世界上最大的艺术和工艺用品商店:MisterArt.com
2018/07/13 全球购物
英国奢侈品牌时尚购物平台:Farfetch(支持中文)
2020/02/18 全球购物
汉语言文学毕业生求职信
2013/10/01 职场文书
大学生暑期实践感言
2014/02/26 职场文书
护士长竞聘演讲稿
2014/04/30 职场文书
金融专业毕业生自荐信
2014/06/26 职场文书
出纳工作检讨书
2014/10/18 职场文书
小学数学教学随笔
2015/08/14 职场文书
python基础之爬虫入门
2021/05/10 Python
python基础学习之递归函数知识总结
2021/05/26 Python
Nginx配置使用详解
2022/07/07 Servers