用户登录
用户注册

分享至

一文帮你理解PReact10.5.13源码

  • 作者: 爱如凉水
  • 来源: 51数据库
  • 2021-08-31

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:
      // http://www.51sjk.com/Upload/Articles/1/0/258/258222_20210630003144210.jpg
      // 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:
 // http://www.all.com/files/Articles/416/0/183/183754_20210624102214763.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函数。

所以源码中,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部分比较复杂,整体整理了一张大图

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

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

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

软件
前端设计
程序设计
Java相关