願你的將來純淨明朗,像你此刻可愛的目光。—— 普希金react
咱們曾探尋過物種起源,咱們也想象過將來要去向何方。一個程序,它也有生與死,輪迴不止git
React
的鮮活生命起源於 ReactDOM.render
,這個過程會爲它的一輩子儲備好不少必需品,咱們順着這個線索,一探嬰兒般 React
應用誕生之初的悅然。github
更新建立的操做咱們總結爲如下兩種場景api
串聯該內容,一圖以蔽之微信
首先看到 react-dom/client/ReactDOM
中對於 ReactDOM
的定義,其中包含咱們熟知的方法、不穩定方法以及即將廢棄方法。數據結構
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節點,第三個參數爲回調函數。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批量更新後續介紹)ide
從這部分源碼咱們不難看出,render
和 createProtal
的用法的聯繫,經過DOM容器建立Root節點的形式函數
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建立更新的核心流程,任務調度咱們下一章節再見。
我是合一,英雄再會!