这篇文章主要经过源码的方式去讲述reactAPI,主要是在react(v16.12.0)这个包中的源码,不涉及react-dom的代码,react-dom会在后面去讲,而在讲述API的时候也不会过多的去讲解这个API的使用方式。而在react这个包里面的API其实更多的只是定义一些组件的type去供给react-dom执行真正更新逻辑的时候使用,所以可能会缺乏一些API源码并无包含到真正执行逻辑的讲解。react
const React = { Children: { map, forEach, count, toArray, only, }, createRef, Component, PureComponent, createContext, forwardRef, lazy, memo, useCallback, useContext, useEffect, useImperativeHandle, useDebugValue, useLayoutEffect, useMemo, useReducer, useRef, useState, Fragment: REACT_FRAGMENT_TYPE, Profiler: REACT_PROFILER_TYPE, StrictMode: REACT_STRICT_MODE_TYPE, Suspense: REACT_SUSPENSE_TYPE, createElement: createElement, cloneElement: cloneElement, createFactory: createFactory, isValidElement: isValidElement, version: ReactVersion, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals, };
以上就是全部react包所暴露出来的APIapi
从上图能够清晰大体的了解该API的调用站栈流程数组
const POOL_SIZE = 10; // 对象池最大数量 const traverseContextPool = []; // 缓存对象,重复使用,减小内存开销以及重复生明对象
function forEachChildren(children, forEachFunc, forEachContext) { // 判断children是否存在 if (children == null) { return children; } // 从context pool中获取对象 const traverseContext = getPooledTraverseContext( null, null, forEachFunc, forEachContext ); // 开始遍历 traverseAllChildren(children, forEachSingleChild, traverseContext); // 释放缓存 releaseTraverseContext(traverseContext); }
以上是这个api的一个大体流程,下面再看下几个调用栈分别作了什么缓存
function getPooledTraverseContext( mapResult, keyPrefix, mapFunction, mapContext ) { if (traverseContextPool.length) { const traverseContext = traverseContextPool.pop(); traverseContext.result = mapResult; traverseContext.keyPrefix = keyPrefix; traverseContext.func = mapFunction; traverseContext.context = mapContext; traverseContext.count = 0; return traverseContext; } else { return { result: mapResult, keyPrefix: keyPrefix, func: mapFunction, context: mapContext, count: 0 }; } }
上面这个函数很简单,不用了解的太过于复杂,它主要先看traverseContextPool中是否有能够用的对象,若是有则取出第一个,并进行赋值返回,若是没有则返回一个全新的对象app
function traverseAllChildrenImpl( children, nameSoFar, callback, traverseContext ) { const type = typeof children; if (type === "undefined" || type === "boolean") { children = null; } let invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case "string": case "number": invokeCallback = true; break; case "object": switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { callback(traverseContext, children); return 1; } let child; let nextName; let subtreeCount = 0; const nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (let i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl( child, nextName, callback, traverseContext ); } } else { const iteratorFn = getIteratorFn(children); if (typeof iteratorFn === "function") { const iterator = iteratorFn.call(children); let step; let ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl( child, nextName, callback, traverseContext ); } } else { } } return subtreeCount; }
function forEachSingleChild(bookKeeping, child) { const { func, context } = bookKeeping; func.call(context, child, bookKeeping.count++); }
// 释放context缓存 function releaseTraverseContext(traverseContext) { traverseContext.result = null; traverseContext.keyPrefix = null; traverseContext.func = null; traverseContext.context = null; traverseContext.count = 0; // 若是Context Pool小于最大值,则保留对象,防止对象重复声明 if (traverseContextPool.length < POOL_SIZE) { traverseContextPool.push(traverseContext); } }
从上图上能够看到 其实map和forEach差很少,惟一的区别只是在最外层多了一个大的递归,为了扁平化map的返回值,若是已经了解了forEach,下面不少重复的步骤能够跳过dom
function mapChildren(children, func, context) { if (children == null) { return children; } const result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; }
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { let escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } const traverseContext = getPooledTraverseContext( array, escapedPrefix, func, context, ); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); releaseTraverseContext(traverseContext); }
这里的几个步骤几乎和forEach一摸同样就不重复说明了,惟一不一样的是forEach调用的是forEachSingleChild,而这边调用的是mapSingleChildIntoContext下面看下这个函数ide
function mapSingleChildIntoContext(bookKeeping, child, childKey) { const { result, keyPrefix, func, context } = bookKeeping; let mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, c => c); } else if (mappedChild != null) { // 验证是不是react对象,主要是经过对象上的$$typeof属性 if (isValidElement(mappedChild)) { // 返回一个全新的reactElement mappedChild = cloneAndReplaceKey(mappedChild); } result.push(mappedChild); } }
count 函数特别简单,就下面三行代码函数
function countChildren(children) { return traverseAllChildren(children, () => null, null); }
function toArray(children) { const result = []; mapIntoWithKeyPrefixInternal(children, result, null, child => child); return result; }
这个API感受并无什么用性能
function onlyChild(children) { invariant( isValidElement(children), 'React.Children.only expected to receive a single React element child.', ); return children; }
这个API估计一看代码就懂,就不解释了,直接贴spa
export function createRef() { const refObject = { current: null }; return refObject; }
累了先写到这里了,我会尽可能把这个包的内容尽快写完,而后开始写react-dom中的内容