愿你的将来纯净明朗,像你此刻可爱的目光。—— 普希金react
咱们曾探寻过物种起源,咱们也想象过将来要去向何方。一个程序,它也有生与死,轮回不止git
React
的鲜活生命起源于 ReactDOM.render
,这个过程会为它的一辈子储备好不少必需品,咱们顺着这个线索,一探婴儿般 React
应用诞生之初的悦然。github
更新建立的操做咱们总结为如下两种场景api
串联该内容,一图以蔽之微信
首先看到 react-dom/client/ReactDOM
中对于 ReactDOM
的定义,其中包含咱们熟知的方法、不稳定方法以及即将废弃方法。markdown
const ReactDOM: Object = { createPortal, // Legacy findDOMNode, hydrate, render, unstable_renderSubtreeIntoContainer, unmountComponentAtNode, // Temporary alias since we already shipped React 16 RC with it. // TODO: remove in React 17. unstable_createPortal(...args) { // ... return createPortal(...args); }, unstable_batchedUpdates: batchedUpdates, flushSync: flushSync, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { // ... }, }; 复制代码
此处方法均来自 ./ReactDOMLegacy
,render
方法定义很简单,正如咱们常使用的那样,第一个参数是组件,第二个参数为组件所要挂载的DOM节点,第三个参数为回调函数。数据结构
export function render( element: React$Element<any>, container: DOMContainer, callback: ?Function, ) { // ... return legacyRenderSubtreeIntoContainer( null, element, container, false, callback, ); } function legacyRenderSubtreeIntoContainer( parentComponent: ?React$Component<any, any>, children: ReactNodeList, container: DOMContainer, forceHydrate: boolean, callback: ?Function, ) { // TODO: Without `any` type, Flow says "Property cannot be accessed on any // member of intersection type." Whyyyyyy. let root: RootType = (container._reactRootContainer: any); let fiberRoot; if (!root) { // Initial mount root = container._reactRootContainer = legacyCreateRootFromDOMContainer( container, forceHydrate, ); fiberRoot = root._internalRoot; if (typeof callback === 'function') { const originalCallback = callback; callback = function() { const instance = getPublicRootInstance(fiberRoot); originalCallback.call(instance); }; } // 初次渲染,不会将更新标记为batched. unbatchedUpdates(() => { updateContainer(children, fiberRoot, parentComponent, callback); }); } else { fiberRoot = root._internalRoot; if (typeof callback === 'function') { const originalCallback = callback; callback = function() { const instance = getPublicRootInstance(fiberRoot); originalCallback.call(instance); }; } // Update updateContainer(children, fiberRoot, parentComponent, callback); } return getPublicRootInstance(fiberRoot); } 复制代码
这段代码咱们不难发现,调用 ReactDOM.render
时,返回的 parentComponent
是 null,而且初次渲染,不会进行批量策略的更新,而是须要尽快的完成。(batchedUpdates批量更新后续介绍)dom
从这部分源码咱们不难看出,render
和 createProtal
的用法的联系,经过DOM容器建立Root节点的形式ide
function legacyCreateRootFromDOMContainer( container: DOMContainer, forceHydrate: boolean, ): RootType { const shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content. if (!shouldHydrate) { let warned = false; let rootSibling; while ((rootSibling = container.lastChild)) { // ... container.removeChild(rootSibling); } } return createLegacyRoot( container, shouldHydrate ? { hydrate: true, } : undefined, ); } 复制代码
createLegacyRoot
定义于 ./ReactDOMRoot
中,指定了建立的DOM容器和一些option设置,最终会返回一个 ReactDOMBlockingRoot
。函数
export function createLegacyRoot( container: DOMContainer, options?: RootOptions, ): RootType { return new ReactDOMBlockingRoot(container, LegacyRoot, options); } function ReactDOMBlockingRoot( container: DOMContainer, tag: RootTag, options: void | RootOptions, ) { this._internalRoot = createRootImpl(container, tag, options); } function createRootImpl( container: DOMContainer, tag: RootTag, options: void | RootOptions, ) { // Tag is either LegacyRoot or Concurrent Root // ... const root = createContainer(container, tag, hydrate, hydrationCallbacks); // ... return root; } 复制代码
关键点在于,方法最终调用了 createContainer
来建立root,而该方法中会建立咱们上一节所介绍的 FiberRoot
,该对象在后续的更新调度过程当中起着很是重要的做用,到更新调度内容咱们详细介绍。
在这部分咱们看到了两个方法,分别是:createContainer、 updateContainer,均出自 react-reconciler/inline.dom
, 最终定义在 ``react-reconciler/src/ReactFiberReconciler` 。建立方法很简单,以下
export function createContainer( containerInfo: Container, tag: RootTag, hydrate: boolean, hydrationCallbacks: null | SuspenseHydrationCallbacks, ): OpaqueRoot { return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks); } 复制代码
咱们继续往下看,紧跟着能看到 updateContainer
方法,该方法定义了更新相关的操做,其中最重要的一个点就是 expirationTime ,直接译为中文是过时时间,咱们想一想,此处为什么要过时时间,这个过时的含义是什么呢?这个过时时间是如何计算的呢?继续往下咱们能够看到,computeExpirationForFiber
方法用于过时时间的计算,咱们先将源码片断放在此处。
export function updateContainer( element: ReactNodeList, container: OpaqueRoot, parentComponent: ?React$Component<any, any>, callback: ?Function, ): ExpirationTime { const current = container.current; const currentTime = requestCurrentTimeForUpdate(); // ... const suspenseConfig = requestCurrentSuspenseConfig(); const expirationTime = computeExpirationForFiber( currentTime, current, suspenseConfig, ); // ... const context = getContextForSubtree(parentComponent); if (container.context === null) { container.context = context; } else { container.pendingContext = context; } // ... const update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property // being called "element". update.payload = {element}; callback = callback === undefined ? null : callback; if (callback !== null) { warningWithoutStack( typeof callback === 'function', 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback, ); update.callback = callback; } enqueueUpdate(current, update); scheduleWork(current, expirationTime); return expirationTime; } 复制代码
计算完更新超时时间,然后建立更新对象 createUpdate
,进而将element绑定到update对象上,若是存在回调函数,则将回调函数也绑定到update对象上。update对象建立完成,将update添加到UpdateQueue中,关于update和UpdateQueue数据结构见上一节讲解。至此,开始任务调度。
这两个方法绑定在咱们当初定义React的文件中,具体定义在 react/src/ReactBaseClasses
中,以下
Component.prototype.setState = function(partialState, callback) { // ... this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; Component.prototype.forceUpdate = function(callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; 复制代码
这就是为什么React基础上拓展React-Native能轻松自如,由于React只是作了一些规范和结构设定,具体实现是在React-Dom或React-Native中,如此达到了平台适配性。
Class组件的更新使用 this.setState
,这个api咱们早已烂熟于心,对于对象组件的更新建立,定义在 react-reconciler/src/ReactFiberClassComponent.js
,classComponentUpdater对象定义了 enqueueSetState
与 enqueueReplaceState
以及 enqueueForceUpdate
对象方法,观察这两个方法会发现,不一样在于enqueueReplaceState
和 enqueueForceUpdate
会在建立的update对象绑定一个tag,用于标志更新的类型是 ReplaceState
仍是 ForceUpdate
,具体实现咱们一块儿来看代码片断。
const classComponentUpdater = { isMounted, enqueueSetState(inst, payload, callback) { const fiber = getInstance(inst); const currentTime = requestCurrentTimeForUpdate(); const suspenseConfig = requestCurrentSuspenseConfig(); const expirationTime = computeExpirationForFiber( currentTime, fiber, suspenseConfig, ); const update = createUpdate(expirationTime, suspenseConfig); update.payload = payload; if (callback !== undefined && callback !== null) { // ... update.callback = callback; } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, enqueueReplaceState(inst, payload, callback) { const fiber = getInstance(inst); const currentTime = requestCurrentTimeForUpdate(); const suspenseConfig = requestCurrentSuspenseConfig(); const expirationTime = computeExpirationForFiber( currentTime, fiber, suspenseConfig, ); const update = createUpdate(expirationTime, suspenseConfig); update.tag = ReplaceState; update.payload = payload; if (callback !== undefined && callback !== null) { // ... update.callback = callback; } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, enqueueForceUpdate(inst, callback) { const fiber = getInstance(inst); const currentTime = requestCurrentTimeForUpdate(); const suspenseConfig = requestCurrentSuspenseConfig(); const expirationTime = computeExpirationForFiber( currentTime, fiber, suspenseConfig, ); const update = createUpdate(expirationTime, suspenseConfig); update.tag = ForceUpdate; if (callback !== undefined && callback !== null) { // ... update.callback = callback; } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, }; 复制代码
咱们也能发现,其实经过setState更新的操做实现和ReactDOM.render基本一致。
tag
、callback
expirationTime用于React在调度和渲染过程,优先级判断,针对不一样的操做,有不一样响应优先级,这时咱们经过 currentTime: ExpirationTime
变量与预约义的优先级EXPIRATION常量计算得出expirationTime。难道currentTime如咱们平时糟糕代码中的 Date.now()
?错!如此操做会产生频繁计算致使性能下降,所以咱们定义currentTime的计算规则。
export function requestCurrentTimeForUpdate() { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // We're inside React, so it's fine to read the actual time. return msToExpirationTime(now()); } // We're not inside React, so we may be in the middle of a browser event. if (currentEventTime !== NoWork) { // Use the same start time for all updates until we enter React again. return currentEventTime; } // This is the first update since React yielded. Compute a new start time. currentEventTime = msToExpirationTime(now()); return currentEventTime; } 复制代码
该方法定义了如何去得到当前时间,now
方法由 ./SchedulerWithReactIntegration
提供,对于now方法的定义彷佛不太好找,咱们经过断点调试 Scheduler_now
,最终可以发现时间的获取是经过 window.performance.now()
, 紧接着找寻到 msToExpirationTime
定义在 ReactFiberExpirationTime.js
,定义了expirationTime相关处理逻辑。
阅读到 react-reconciler/src/ReactFilberExpirationTime
,对于expirationTime的计算有三个不一样方法,分别为:computeAsyncExpiration
、computeSuspenseExpiration
、computeInteractiveExpiration
。这三个方法均接收三个参数,第一个参数均为以上获取的 currentTime
,第二个参数为约定的超时时间,第三个参数与批量更新的粒度有关。
export const Sync = MAX_SIGNED_31_BIT_INT; export const Batched = Sync - 1; const UNIT_SIZE = 10; const MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms. export function msToExpirationTime(ms: number): ExpirationTime { // Always add an offset so that we don't clash with the magic number for NoWork. return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0); } export function expirationTimeToMs(expirationTime: ExpirationTime): number { return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE; } function ceiling(num: number, precision: number): number { return (((num / precision) | 0) + 1) * precision; } function computeExpirationBucket( currentTime, expirationInMs, bucketSizeMs, ): ExpirationTime { return ( MAGIC_NUMBER_OFFSET - ceiling( MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE, ) ); } // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update // the names to reflect. export const LOW_PRIORITY_EXPIRATION = 5000; export const LOW_PRIORITY_BATCH_SIZE = 250; export function computeAsyncExpiration( currentTime: ExpirationTime, ): ExpirationTime { return computeExpirationBucket( currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE, ); } export function computeSuspenseExpiration( currentTime: ExpirationTime, timeoutMs: number, ): ExpirationTime { // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time? return computeExpirationBucket( currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE, ); } export const HIGH_PRIORITY_EXPIRATION = __DEV__ ? 500 : 150; export const HIGH_PRIORITY_BATCH_SIZE = 100; export function computeInteractiveExpiration(currentTime: ExpirationTime) { return computeExpirationBucket( currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE, ); } 复制代码
重点在于 ceil
方法的定义,方法传递两个参数,须要求值的number和指望精度precision,不妨随意带入两个值观察该函数的做用,number = 100,precision = 10,那么函数返回值为 (((100 / 10) | 0) + 1) * 10,咱们保持precision值不变,更改number会发现,当咱们的值在100-110之间时,该函数返回的值相同。哦!此时恍然大悟,原来这个方法就是保证在同一个bucket中的更新获取到相同的过时时间 expirationTime
,就可以实如今较短期间隔内的更新建立可以__合并处理__。
关于超时时间的处理是很复杂的,除了咱们看到的 expirationTime
,还有 childExpirationTime
、root.firstPendingTime
、root.lastExpiredTime
、root.firstSuspendedTime
、root.lastSuspendedTime
,root下的相关属性标记了其下子节点fiber的expirationTime的次序,构成处理优先级的次序,childExpirationTime
则是在遍历子树时,更新其 childExpirationTime
值为子节点 expirationTime
。
以上是React建立更新的核心流程,任务调度咱们下一章节再见。
我是合一,英雄再会!