前言
React的定位是一個構建用戶界面的JavaScript類庫,它使用JavaScript語言開發UI組件,可以使用多種方式渲染這些組件,輸出用戶界面,較大程度的達到了跨技術棧跨平臺的兼容重用:
We don’t make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code.
現在的React已然在以下幾個方面發揮的都很不錯:
- React Web應用用戶界面開發;
- React Native App用戶界面開發;
- Node.js服務端渲染;
在這些不同場景,渲染的主體很明顯是不一樣的,有諸如web應用的DOM渲染,React Native的原生View渲染,服務端字符串渲染等,要做到兼容適應多種不同渲染環境,很顯然,React不能侷限固定渲染UI的方式。
React核心內容也確實只包括定義組件相關的內容和API,源碼可以查看,實際項目中,可以看到首先需要使用如下代碼:
import React from 'react';
這句代碼做的就是引入了React核心源碼模塊。
渲染
上一節已經說到React核心內容只涉及如何定義組件,並不涉及具體的組件渲染(即輸出用戶界面),這需要額外引入渲染模塊,以渲染React定義的組件:
-
React DOM渲染模塊:將React組件渲染爲DOM,然後可以被瀏覽器處理呈現給用戶,這就是通常在web應用中引入的
react-dom
模塊:import React from 'react'; import { render } from 'react-dom'; import App from './apps/App.js'; render( <App />, document.getElementById('mainBox') );
如上代碼,
App
是使用React核心模塊定義的組件,然後使用react-dom
渲染模塊提供的render
方法將其渲染爲DOM輸出至頁面。 -
React Native 渲染:將React組件渲染爲移動端原生View,在React Native應用中引入
react-native
模塊,它提供相應渲染方法可以渲染React組件:import { AppRegistry } from 'react-native'; import App from './src/app.js'; AppRegistry.registerComponent('fuc', () => App);
如上,
App
是React根組件,使用react-native
渲染器的AppRegistry.registerComponent
方法將其渲染爲原生View。 -
React測試渲染:將React組件渲染爲JSON樹,用來完成Jest的快照測試,內容在
react-test-renderer
模塊:import ReactTestRenderer from 'react-test-renderer'; const renderer = ReactTestRenderer.create( <Link page="https://www.facebook.com/">Facebook</Link> ); console.log(renderer.toJSON()); // { type: 'a', // props: { href: 'https://www.facebook.com/' }, // children: [ 'Facebook' ] }
-
React矢量圖渲染:將React組件渲染爲對應的適量圖(ART庫);
web React應用是最常見的,也是最易於理解的,所以本篇後文均從React-DOM渲染器角度解析Fiber。
調和(Reconciliation)
如前面兩節所述,React核心是定義組件,渲染組件方式由環境決定,定義組件,組件狀態管理,生命週期方法管理,組件更新等應該跨平臺一致處理,不受渲染環境影響,這部分內容統一由調和器(Reconciler)處理,源碼傳送,不同渲染器都會使用該模塊。調和器主要作用就是在組件狀態變更時,調用組件樹各組件的render
方法,渲染,卸載組件。
Stack Reconciler
我們知道瀏覽器渲染引擎是單線程的,在React 15.x版本及之前版本,計算組件樹變更時將會阻塞整個線程,整個渲染過程是連續不中斷完成的,而這時的其他任務都會被阻塞,如動畫等,這可能會使用戶感覺到明顯卡頓,比如當你在訪問某一網站時,輸入某個搜索關鍵字,更優先的應該是交互反饋或動畫效果,如果交互反饋延遲200ms,用戶則會感覺較明顯的卡頓,而數據響應晚200毫秒並沒太大問題。這個版本的調和器可以稱爲棧調和器(Stack Reconciler),其調和算法大致過程見React Diff算法 和React Stack Reconciler實現。
Stack Reconcilier的主要缺陷就是不能暫停渲染任務,也不能切分任務,無法有效平衡組件更新渲染與動畫相關任務間的執行順序,即不能劃分任務優先級,有可能導致重要任務卡頓,動畫掉幀等問題。
Fiber Reconciler
React 16版本提出了一個更先進的調和器,它允許渲染進程分段完成,而不必須一次性完成,中間可以返回至主進程控制執行其他任務。而這是通過計算部分組件樹的變更,並暫停渲染更新,詢問主進程是否有更高需求的繪製或者更新任務需要執行,這些高需求的任務完成後纔開始渲染。這一切的實現是在代碼層引入了一個新的數據結構-Fiber對象,每一個組件實例對應有一個fiber實例,此fiber實例負責管理組件實例的更新,渲染任務及與其他fiber實例的聯繫。
這個新推出的調和器就叫做纖維調和器(Fiber Reconciler),它提供的新功能主要有:
- 可切分,可中斷任務;
- 可重用各分階段任務,且可以設置優先級;
- 可以在父子組件任務間前進後退切換任務;
render
方法可以返回多元素(即可以返回數組);- 支持異常邊界處理異常;
說了這麼多,終於要正式出場本篇主角:Fiber了,React最新版本已經升到16.1.1,估計16.x穩定版不會太遠,讓我們先睹爲快吧。
Fiber與JavaScript
前面說到Fiber可以異步實現不同優先級任務的協調執行,那麼對於DOM渲染器而言,在JavaScript層是否提供這種方式呢,還是說只能使用setTimeout模擬呢?目前新版本主流瀏覽器已經提供了可用API:requestIdleCallback
和requestAnimationFrame
:
- requestIdleCallback: 在線程空閒時期調度執行低優先級函數;
- requestAnimationFrame: 在下一個動畫幀調度執行高優先級函數;
空閒期(Idle Period)
通常,客戶端線程執行任務時會以幀的形式劃分,大部分設備控制在30-60幀是不會影響用戶體驗;在兩個執行幀之間,主線程通常會有一小段空閒時間,requestIdleCallback
可以在這個空閒期(Idle Period)調用空閒期回調(Idle Callback),執行一些任務。
Fiber與requestIdleCallback
Fiber所做的就是需要分解渲染任務,然後根據優先級使用API調度,異步執行指定任務:
- 低優先級任務由
requestIdleCallback
處理; - 高優先級任務,如動畫相關的由
requestAnimationFrame
處理; requestIdleCallback
可以在多個空閒期調用空閒期回調,執行任務;requestIdleCallback
方法提供deadline,即任務執行限制時間,以切分任務,避免長時間執行,阻塞UI渲染而導致掉幀;
具體執行任務實現源碼傳送:
-
若支持原生API,具體原生實現見上文給出的鏈接:
rIC = window.requestIdleCallback; cIC = window.cancelIdleCallback; export {now, rIC, cIC};
-
若不支持,則自定義實現:
let isIdleScheduled = false; // 是否在執行空閒期回調 let frameDeadlineObject = { didTimeout: false, timeRemaining() { // now = Performance.now || Date.now const remaining = frameDeadline - now(); // 計算得到當前幀運行剩餘時間 return remaining > 0 ? remaining : 0; }, }; // 幀回調 const animationTick = function(rafTime) { ... if (!isIdleScheduled) { // 不在執行空閒期回調,表明可以調用空閒期回調 isIdleScheduled = true; // 執行Idle空閒期回調 idleTick(); } }; // 空閒期回調 const idleTick = function() { // 重置爲false,表明可以調用空閒期回調 isIdleScheduled = false; const currentTime = now(); if (frameDeadline - currentTime <= 0) { // 幀到期時間小於當前時間,說明已過期 if (timeoutTime !== -1 && timeoutTime <= currentTime) { // 此幀已過期,且發生任務處理函數(執行具體任務,傳入的回調)的超時 // 需要執行任務處理,下文將調用; frameDeadlineObject.didTimeout = true; } else { // 幀已過期,但沒有發生任務處理函數的超時,暫時不調用任務處理函數 if (!isAnimationFrameScheduled) { // 當前沒有調度別的幀回調函數 // 調度下一幀 isAnimationFrameScheduled = true; requestAnimationFrame(animationTick); } // Exit without invoking the callback. return; } } else { // 這一幀還有剩餘時間 // 標記未超時,之後調用任務處理函數 frameDeadlineObject.didTimeout = false; } // 緩存的任務處理函數 timeoutTime = -1; const callback = scheduledRICCallback; scheduledRICCallback = null; if (callback !== null) { // 執行回調 callback(frameDeadlineObject); } } // 自定義模擬requestIdleCallback rIC = function( callback: (deadline: Deadline) => void, // 傳入的任務處理函數參數 options?: {timeout: number} // 其他參數 ) { // 回調函數 scheduledRICCallback = callback; if (options != null && typeof options.timeout === 'number') { // 計算過期時間 timeoutTime = now() + options.timeout; } if (!isAnimationFrameScheduled) { // 當前沒有調度別的幀回調函數 isAnimationFrameScheduled = true; // 初始開始執行幀回調 requestAnimationFrame(animationTick); } return 0; };
frameDeadline
:是以啓發法,從30fps(即30幀)開始調整得到的更適於當前環境的一幀限制時間;timeRemaining
:計算requestIdleCallback
此次空閒(幀)執行任務剩餘時間,即距離deadline的時間;options.timeout
:Fiber內部調用rIC
API執行異步任務時,傳遞的任務到期時間參數;frameDeadlineObject
:計算得到的某一幀可用時間對象,兩個屬性分別表示:- didTimeout:傳入的異步任務 處理函數是否超時;
- timeRemaining:當前幀可執行任務處理函數的剩餘空閒時間;
frameDeadlineObject
對象是基於傳入的timeout
參數和此模塊內部自調整得到的frameDeadline
參數計算得出;
Fiber與組件
我們已經知道了Fiber的功能及其主要特點,那麼其如何和組件聯繫,並且如何實現效果的呢,以下幾點可以概括:
- React應用中的基礎單元是組件,應用以組件樹形式組織,渲染組件;
- Fiber調和器基礎單元則是fiber(調和單元),應用以fiber樹形式組織,應用Fiber算法;
- 組件樹和fiber樹結構對應,一個組件實例有一個對應的fiber實例;
- Fiber負責整個應用層面的調和,fiber實例負責對應組件的調和;
注意Fiber與fiber的區別,Fiber是指調和器算法,fiber則是調和器算法組成單元,和組件與應用關係類似,每一個組件實例會有對應的fiber實例負責該組件的調和。
Fiber數據結構
截止目前,我們對Fiber應該有了初步的瞭解,在具體介紹Fiber的實現與架構之前,準備先簡單介紹一下Fiber的數據結構,數據結構能一定程度反映其整體工作架構。
其實,一個fiber就是一個JavaScript對象,以鍵值對形式存儲了一個關聯組件的信息,包括組件接收的props,維護的state,最後需要渲染出的內容等。接下來我們將介Fiber對象的主要屬性。
Fiber對象
首先Fiber對象的定義如下:
// 一個Fiber對象作用於一個組件
export type Fiber = {|
// 標記fiber類型tag.
tag: TypeOfWork,
// fiber對應的function/class/module類型組件名.
type: any,
// fiber所在組件樹的根組件FiberRoot對象
stateNode: any,
// 處理完當前fiber後返回的fiber,
// 返回當前fiber所在fiber樹的父級fiber實例
return: Fiber | null,
// fiber樹結構相關鏈接
child: Fiber | null,
sibling: Fiber | null,
index: number,
// 當前處理過程中的組件props對象
pendingProps: any,
// 緩存的之前組件props對象
memoizedProps: any, // The props used to create the output.
// The state used to create the output
memoizedState: any,
// 組件狀態更新及對應回調函數的存儲隊列
updateQueue: UpdateQueue<any> | null,
// 描述當前fiber實例及其子fiber樹的數位,
// 如,AsyncUpdates特殊字表示默認以異步形式處理子樹,
// 一個fiber實例創建時,此屬性繼承自父級fiber,在創建時也可以修改值,
// 但隨後將不可修改。
internalContextTag: TypeOfInternalContext,
// 更新任務的最晚執行時間
expirationTime: ExpirationTime,
// fiber的版本池,即記錄fiber更新過程,便於恢復
alternate: Fiber | null,
// Conceptual aliases
// workInProgress : Fiber -> alternate The alternate used for reuse happens
// to be the same as work in progress.
|};
- type & key:同React元素的值;
- type:描述fiber對應的React組件;
- 對於組合組件:值爲function或class組件本身;
- 對於原生組件(div等):值爲該元素類型字符串;
- key:調和階段,標識fiber,以檢測是否可重用該fiber實例;
- child & sibling:組件樹,對應生成fiber樹,類比的關係;
- pendingProps & memoizedProps:分別表示組件當前傳入的及之前的props;
- return:返回當前fiber所在fiber樹的父級fiber實例,即當前組件的父組件對應的fiber;
- alternate:fiber的版本池,即記錄fiber更新過程,便於恢復重用;
- workInProgress:正在處理的fiber,概念上叫法,實際上沒有此屬性;
alternate fiber
可以理解爲一個fiber版本池,用於交替記錄組件更新(切分任務後變成多階段更新)過程中fiber的更新,因爲在組件更新的各階段,更新前及更新過程中fiber狀態並不一致,在需要恢復時(如,發生衝突),即可使用另一者直接回退至上一版本fiber。
- 使用alternate屬性雙向連接一個當前fiber和其work-in-progress,當前fiber實例的alternate屬性指向其work-in-progress,work-in-progress的alternate屬性指向當前穩定fiber;
- 當前fiber的替換版本是其work-in-progress,work-in-progress的交替版本是當前fiber;
- 當work-in-progress更新一次後,將同步至當前fiber,然後繼續處理,同步直至任務完成;
- work-in-progress指向處理過程中的fiber,而當前fiber總是維護處理完成的最新版本的fiber。
創建Fiber實例
創建fiber實例即返回一個帶有上一小節描述的諸多屬性的JavaScript對象,FiberNode
即根據傳入的參數構造返回一個初始化的對象:
var createFiber = function(
tag: TypeOfWork,
key: null | string,
internalContextTag: TypeOfInternalContext,
) {
return new FiberNode(tag, key, internalContextTag);
};
創建alternate fiber以處理任務的實現如下:
// 創建一個alternate fiber處理任務
export function createWorkInProgress(
current: Fiber,
pendingProps: any,
expirationTime: ExpirationTime,
) {
let workInProgress = current.alternate;
if (workInProgress === null) {
workInProgress = createFiber(
current.tag,
current.key,
current.internalContextTag,
);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
// 形成alternate關係,互相交替模擬版本池
workInProgress.alternate = current;
current.alternate = workInProgress;
}
workInProgress.expirationTime = expirationTime;
workInProgress.pendingProps = pendingProps;
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.updateQueue = current.updateQueue;
...
return workInProgress;
}
Fiber類型
上一小節,Fiber對象中有個tag
屬性,標記fiber類型,而fiber實例是和組件對應的,所以其類型基本上對應於組件類型,源碼見ReactTypeOfWork模塊:
export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
export const IndeterminateComponent = 0; // 尚不知是類組件還是函數式組件
export const FunctionalComponent = 1; // 函數式組件
export const ClassComponent = 2; // Class類組件
export const HostRoot = 3; // 組件樹根組件,可以嵌套
export const HostPortal = 4; // 子樹. Could be an entry point to a different renderer.
export const HostComponent = 5; // 標準組件,如地div, span等
export const HostText = 6; // 文本
export const CallComponent = 7; // 組件調用
export const CallHandlerPhase = 8; // 調用組件方法
export const ReturnComponent = 9; // placeholder(佔位符)
export const Fragment = 10; // 片段
在調度執行任務的時候會根據不同類型fiber,即fiber.tag值進行不同處理。
FiberRoot對象
FiberRoot
對象,主要用來管理組件樹組件的更新進程,同時記錄組件樹掛載的DOM容器相關信息,具體定義見ReactFiberRoot模塊:
export type FiberRoot = {
// fiber節點的容器元素相關信息,通常會直接傳入容器元素
containerInfo: any,
// 當前fiber樹中激活狀態(正在處理)的fiber節點,
current: Fiber,
// 此節點剩餘的任務到期時間
remainingExpirationTime: ExpirationTime,
// 更新是否可以提交
isReadyForCommit: boolean,
// 準備好提交的已處理完成的work-in-progress
finishedWork: Fiber | null,
// 多組件樹FirberRoot對象以單鏈表存儲鏈接,指向下一個需要調度的FiberRoot
nextScheduledRoot: FiberRoot | null,
};
創建FiberRoot實例
import {
ClassComponent,
HostRoot
} from 'shared/ReactTypeOfWork';
// 創建返回一個初始根組件對應的fiber實例
function createHostRootFiber(): Fiber {
// 創建fiber
const fiber = createFiber(HostRoot, null, NoContext);
return fiber;
}
export function createFiberRoot(
containerInfo: any,
hydrate: boolean,
) {
// 創建初始根組件對應的fiber實例
const uninitializedFiber = createHostRootFiber();
// 組件樹根組件的FiberRoot對象
const root = {
// 根組件對應的fiber實例
current: uninitializedFiber,
containerInfo: containerInfo,
pendingChildren: null,
remainingExpirationTime: NoWork,
isReadyForCommit: false,
finishedWork: null,
context: null,
pendingContext: null,
hydrate,
nextScheduledRoot: null,
};
// 組件樹根組件fiber實例的stateNode指向FiberRoot對象
uninitializedFiber.stateNode = root;
return root;
}
ReactChildFiber
在生成組件樹的FiberRoot對象後,會爲子組件生成各自的fiber實例,這一部分由ReactChildFiber模塊實現:
// 調和(處理更新)子fibers
export const reconcileChildFibers = ChildReconciler(true);
// 掛載(初始化)子fibers
export const mountChildFibers = ChildReconciler(false);
而ChildReconciler
方法所做的則是根據傳入參數判斷是調用初始化子組件fibers邏輯還是執行調和已有子組件fibers邏輯。
ChildReconciler
方法,返回reconcileChildFibers
方法:
- 判斷子級傳遞內容的數據類型,執行不同的處理,這也對應着我們寫React組件時傳遞
props.children
時,其類型可以是對象或數組,字符串,是數字等; - 然後具體根據子組件類型,調用不同的具體調和處理函數;
- 最後返回根據子組件創建或更新得到的fiber實例;
function ChildReconciler(a) {
function reconcileChildFibers(
returnFiber: Fiber, currentFirstChild: Fiber | null,
newChild: any, expirationTime: ExpirationTime,
) {
// Handle object types
const isObject = typeof newChild === 'object' && newChild !== null;
if (isObject) {
// 子組件實例類型,以Symbol符號表示的
switch (newChild.$$typeof) {
// React Element
case REACT_ELEMENT_TYPE:
return placeSingleChild(
reconcileSingleElement(
returnFiber, currentFirstChild,
newChild, expirationTime
)
);
// React組件調用
case REACT_CALL_TYPE:
return placeSingleChild(reconcileSingleCall(...));
// placeholder
case REACT_RETURN_TYPE:
return ...;
case REACT_PORTAL_TYPE:
return ...;
}
}
if (typeof newChild === 'string' || typeof newChild === 'number') {
return placeSingleChild(reconcileSingleTextNode(...));
}
if (isArray(newChild)) {
return reconcileChildrenArray(...);
}
if (getIteratorFn(newChild)) {
return reconcileChildrenIterator(...);
}
...
}
}
Fiber架構
在學習Fiber的時候,我嘗試去閱讀源碼,發現通過這種方式很難快速理解,學習Fiber,而先了解調和器是幹什麼的及調和器在React中的存在形式,然後再學習Fiber的結構及算法實現思路,明白從組件被定義到渲染至頁面它需要做什麼,這也是本篇文章的組織形式。
優先級(ExpirationTime VS PriorityLevel)
我們已經知道Fiber可以切分任務並設置不同優先級,那麼是如何實現劃分優先級的呢,其表現形式什麼呢?
ExpirationTime
Fiber切分任務並調用requestIdleCallback
和requestAnimationFrame
API,保證渲染任務和其他任務,在不影響應用交互,不掉幀的前提下,穩定執行,而實現調度的方式正是給每一個fiber實例設置到期執行時間,不同時間即代表不同優先級,到期時間越短,則代表優先級越高,需要儘早執行。
所謂的到期時間(ExpirationTime),是相對於調度器初始調用的起始時間而言的一個時間段;調度器初始調用後的某一段時間內,需要調度完成這項更新,這個時間段長度值就是到期時間值。
Fiber提供ReactFiberExpirationTime模塊實現到期時間的定義:
export const NoWork = 0; // 沒有任務等待處理
export const Sync = 1; // 同步模式,立即處理任務
export const Never = 2147483647; // Max int32: Math.pow(2, 31) - 1
const UNIT_SIZE = 10; // 過期時間單元(ms)
const MAGIC_NUMBER_OFFSET = 2; // 到期時間偏移量
// 以ExpirationTime特定單位(1單位=10ms)表示的到期執行時間
// 1 unit of expiration time represents 10ms.
export function msToExpirationTime (ms) {
// 總是增加一個偏移量,在ms<10時與Nowork模式進行區別
return ((ms / UNIT_SIZE) | 0) + MAGIC_NUMBER_OFFSET;
}
// 以毫秒錶示的到期執行時間
export function expirationTimeToMs(expirationTime: ExpirationTime) {
return (expirationTime - MAGIC_NUMBER_OFFSET) * UNIT_SIZE;
}
// 向上取整(整數單位到期執行時間)
// precision範圍精度:彌補任務執行時間誤差
function ceiling(num, precision) {
return (((num / precision) | 0) + 1) * precision;
}
// 計算處理誤差時間在內的到期時間
export function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs,) {
return ceiling(
currentTime + expirationInMs / UNIT_SIZE,
bucketSizeMs / UNIT_SIZE
);
}
該模塊提供的功能主要有:
- Sync:同步模式,在UI線程立即執行此類任務,如動畫反饋等;
- 異步模式:
- 轉換:到期時間特定單位和時間單位(ms)的相互轉換;
- 計算:計算包含允許誤差在內的到期時間;
PriorityLevel
其實在15.x版本中出現了對於任務的優先層級劃分,ReactPriorityLevel模塊:
export type PriorityLevel = 0 | 1 | 2 | 3 | 4 | 5;
module.exports = {
NoWork: 0, // No work is pending.
SynchronousPriority: 1, // For controlled text inputs. Synchronous side-effects.
AnimationPriority: 2, // Needs to complete before the next frame.
HighPriority: 3, // Interaction that needs to complete pretty soon to feel responsive.
LowPriority: 4, // Data fetching, or result from updating stores.
OffscreenPriority: 5, // Won't be visible but do the work in case it becomes visible.
};
相對於PriorityLevel的簡單層級劃分,在16.x版本中使用的則是ExpirationTime的到期時間方式表示任務的優先級,可以更好的對任務進行切分,調度。
調度器(Scheduler)
前面介紹調和器主要作用就是在組件狀態變更時,調用組件樹各組件的render
方法,渲染,卸載組件,而Fiber使得應用可以更好的協調不同任務的執行,調和器內關於高效協調的實現,我們可以稱它爲調度器(Scheduler)。
顧名思義,調度器即調度資源以執行指定任務,React應用中應用組件的更新與渲染,需要佔用系統CPU資源,如果不能很好的進行資源平衡,合理調度,優化任務執行策略,那很容易造成CPU這一緊缺資源的消耗和浪費,容易造成頁面卡頓,動畫掉幀,組件更新異常等諸多問題,就像城市交通調度一樣,如果不能有效調度,交通狀況很可能將擁堵不堪。
在React 15.x版本中,組件的狀態變更將直接導致其子組件樹的重新渲染,新版本Fiber算法將在調度器方面進行全面改進,主要的關注點是:
- 合併多次更新:沒有必要在組件的每一個狀態變更時都立即觸發更新任務,有些中間狀態變更其實是對更新任務所耗費資源的浪費,就比如用戶發現錯誤點擊時快速操作導致組件某狀態從A至B再至C,這中間的B狀態變更其實對於用戶而言並沒有意義,那麼我們可以直接合並狀態變更,直接從A至C只觸發一次更新;
- 任務優先級:不同類型的更新有不同優先級,例如用戶操作引起的交互動畫可能需要有更好的體驗,其優先級應該比完成數據更新高;
- 推拉式調度:基於推送的調度方式更多的需要開發者編碼間接決定如何調度任務,而拉取式調度更方便React框架層直接進行全局自主調度;
export default function () {
...
return {
computeAsyncExpiration,
computeExpirationForFiber,
scheduleWork,
batchedUpdates,
unbatchedUpdates,
flushSync,
deferredUpdates,
};
}
如上調度器主要輸出API爲實現調度任務,拉取更新,延遲更新等功能。
調度器與優先級
調度器如何切分任務劃分優先級的呢?在React調和算法中,任務由fiber實例描述,所以要劃分任務優先級,等效於設置fiber的到期時間(expirationTime),調度器內提供了computeExpirationForFiber
方法以計算某一個fiber的到期時間:
import {
NoWork, Sync, Never, msToExpirationTime,
expirationTimeToMs, computeExpirationBucket
} from './ReactFiberExpirationTime';
// 表示下一個要處理的任務的到期時間,默認爲NoWork,即當前沒有正在等待執行的任務;
// Nowork默認更新策略:異步模式下,異步執行任務;同步模式下同步執行任務
let expirationContext = NoWork;
// 下一次渲染到期時間
let nextRenderExpirationTime = NoWork;
// 異步更新
export const AsyncUpdates = 1;
// 初始時間(ms).
const startTime = now();
// ExpirationTime單位表示的當前時間(ExpirationTime單位,初始值傳入0)
let mostRecentCurrentTime = msToExpirationTime(0);
// 計算fiber的到期時間
function computeExpirationForFiber(fiber) {
let expirationTime;
if (isWorking) {
if (isCommitting) {
// 在提交階段的更新任務
// 需要明確設置同步優先級(Sync Priority)
expirationTime = Sync;
} else {
// 在渲染階段發生的更新任務
// 需要設置爲下一次渲染時間的到期時間優先級
expirationTime = nextRenderExpirationTime;
}
} else {
// 不在任務執行階段,需要計算新的過期時間
// 明確傳遞useSyncScheduling爲true表明期望同步調用
// 且fiber.internalContextTag != AsyncUpdates
if (useSyncScheduling && !(fiber.internalContextTag & AsyncUpdates)) {
// 同步更新,設置爲同步標記
expirationTime = Sync;
} else {
// 異步更新,計算異步到期時間
expirationTime = computeAsyncExpiration();
}
}
return expirationTime;
}
- 若當前處於任務提交階段(更新提交至DOM渲染)時,設置當前fiber到期時間爲
Sync
,即同步執行模式; - 若處於DOM渲染階段時,則需要延遲此fiber任務,將fiber到期時間設置爲下一次DOM渲染到期時間;
- 若不在任務執行階段,則需重新設置fiber到期時間:
- 若明確設置
useSyncScheduling
且fiber.internalContextTag
值不等於AsyncUpdates
,則表明是同步模式,設置爲Sync
; - 否則,調用
computeAsyncExpiration
方法重新計算此fiber的到期時間;
- 若明確設置
// 重新計算當前時間(ExpirationTime單位表示)
function recalculateCurrentTime() {
const ms = now() - startTime;
// ExpirationTime單位表示的當前時間
// 時間段值爲 now() - startTime(起始時間)
mostRecentCurrentTime = msToExpirationTime(ms);
return mostRecentCurrentTime;
}
// 計算異步任務的到期時間
function computeAsyncExpiration() {
// 計算得到ExpirationTime單位的當前時間
// 聚合相似的更新在一起
// 更新應該在 ~1000ms,最多1200ms內完成
const currentTime = recalculateCurrentTime();
// 對於每個fiber的期望到期時間的增值,最大值爲1000ms
const expirationMs = 1000;
// 到期時間的可接受誤差時間,200ms
const bucketSizeMs = 200;
// 返回包含誤差時間在內的到期時間
return computeExpirationBucket(currentTime, expirationMs, bucketSizeMs);
}
對於每一個fiber我們期望的到期時間參數是1000ms,另外由於任務執行時間誤差,接受200ms誤差,最後計算得到的到期時間默認返回值爲ExpirationTime單位。
任務調度
上一節介紹了調度器主要提供computeExpirationForFiber
等方法支持計算任務優先級(到期時間),接下來介紹調度器如何調度任務。
React應用更新時,Fiber從當前處理節點,層層遍歷至組件樹根組件,然後開始處理更新,調用前面的
requestIdleCallback
等API執行更新處理。
主要調度邏輯實現在scheduleWork
:
- 通過
fiber.return
屬性,從當前fiber實例層層遍歷至組件樹根組件; - 依次對每一個fiber實例進行到期時間判斷,若大於傳入的期望任務到期時間參數,則將其更新爲傳入的任務到期時間;
- 調用
requestWork
方法開始處理任務,並傳入獲取的組件樹根組件FiberRoot對象和任務到期時間;
// 調度任務
// expirationTime爲期望的任務到期時間
function scheduleWork(fiber, expirationTime: ExpirationTime) {
return scheduleWorkImpl(fiber, expirationTime, false);
}
function scheduleWorkImpl(
fiber, expirationTime
) {
let node = fiber;
while (node !== null) {
// 向上遍歷至根組件fiber實例,並依次更新expirationTime到期時間
if (
node.expirationTime === NoWork ||
node.expirationTime > expirationTime
) {
// 若fiber實例到期時間大於期望的任務到期時間,則更新fiber到期時間
node.expirationTime = expirationTime;
}
// 同時更新alternate fiber的到期時間
if (node.alternate !== null) {
if (
node.alternate.expirationTime === NoWork ||
node.alternate.expirationTime > expirationTime
) {
// 若alternate fiber到期時間大於期望的任務到期時間,則更新fiber到期時間
node.alternate.expirationTime = expirationTime;
}
}
// node.return爲空,說明到達組件樹頂部
if (node.return === null) {
if (node.tag === HostRoot) {
// 確保是組件樹根組件並獲取FiberRoot實例
const root = node.stateNode;
// 請求處理任務
requestWork(root, expirationTime);
} else {
return;
}
}
// 獲取父級組件fiber實例
node = node.return;
}
}
處理任務的requestWork
方法實現如下:
- 首先比較任務剩餘到期時間和期望的任務到期時間,若大於,則更新值;
- 判斷任務期望到期時間(expirationTime),區分同步或異步執行任務;
// 當根節點發生更新時,調度器將調用requestWork方法開始任務處理過程
// It's up to the renderer to call renderRoot at some point in the future.
function requestWork(root: FiberRoot, expirationTime) {
const remainingExpirationTime = root.remainingExpirationTime;
if (remainingExpirationTime === NoWork ||
expirationTime < remainingExpirationTime) {
// 若任務剩餘到期時間大於期望的任務到期時間,則需要更新
root.remainingExpirationTime = expirationTime;
}
if (expirationTime === Sync) {
// 同步
performWork(Sync, null);
} else {
// 異步
scheduleCallbackWithExpiration(expirationTime);
}
}
更新隊列(UpdateQueue)
我們知道如果需要實現組件的異步更新,肯定需要在更新前將更新任務進行存儲,然後異步任務開始的時候讀取更新並實現組件更新,存儲更新任務就需要一個數據結構,最常見的就是棧和隊列,Fiber的實現方式就是隊列。
Fiber切分任務爲多個任務單元(Work Unit)後,需要劃分優先級然後存儲在更新隊列,隨後按優先級進行調度執行。我們知道每一個組件都對應有一個fiber實例,fiber實例即負責管理調度組件的任務單元,所以需要爲每一個組件fiber實例維護一個更新隊列。
Fiber更新隊列由ReactFiberUpdateQueue模塊實現,主要涉及:
- 創建更新隊列;
- 添加更新至更新隊列;
- 添加更新至fiber(即fiber實例對應的更新隊列);
- 處理更新隊列中的更新並返回新狀態對象:
// 一個更新對應的數據結構
export type Update<State> = {
expirationTime: ExpirationTime,
partialState: PartialState<any, any>,
callback: Callback | null,
isReplace: boolean,
isForced: boolean,
next: Update<State> | null,
};
// 更新隊列,以單鏈表形式表示並持久化
// 調度一個更新任務時,將其添加至當前(current)fiber和work-in-progress fiber的更新隊列中;
// 這兩個更新隊列相互獨立但共享同一個持久化數據結構;
// work-in-progress更新隊列通常是current fiber更新隊列的子集;
// 發生調和時,更新任務從work-in-progress fiber更新隊列移除,
// current fiber內的更新任務則保留,當work-in-progress中斷時可以從current fiber恢復;
// 提交完更新時,work-in-progress fiber就會變成current fiber
export type UpdateQueue<State> = {
// 若存在更早添加至隊列的更新未被處理,
// 則此已處理的更新並不會從隊列中移除-先進先出原則
// 所以需要維護baseState,代表第一個未處理的更新的基礎狀態,
// 通常這就是隊列中的第一個更新,因爲在隊列首部的已處理更新會被移除
baseState: State,
// 同理,需要維護最近的未處理的更新的到期時間,
// 即未處理更新中到期時間值最小的
expirationTime: ExpirationTime,
first: Update<State> | null,
last: Update<State> | null,
callbackList: Array<Update<State>> | null,
hasForceUpdate: boolean,
isInitialized: boolean
};
// 添加更新至更新隊列
export function insertUpdateIntoQueue<State>(
queue: UpdateQueue<State>,
update: Update<State>
){
// 添加更新至隊列尾部
if (queue.last === null) {
// 隊列爲空
queue.first = queue.last = update;
} else {
queue.last.next = update;
queue.last = update;
}
if (
queue.expirationTime === NoWork ||
queue.expirationTime > update.expirationTime
) {
// 更新最近到期時間
queue.expirationTime = update.expirationTime;
}
}
// 添加更新至fiber實例
export function insertUpdateIntoFiber<State>(
fiber: Fiber,
update: Update<State>,
) {
// 可以創建兩個獨立的更新隊列
// alternate主要用來保存更新過程中各版本更新隊列,方便崩潰或衝突時回退
const alternateFiber = fiber.alternate;
let queue1 = fiber.updateQueue;
if (queue1 === null) {
// 更新隊列不存在,則創建一個空的更新隊列
queue1 = fiber.updateQueue = createUpdateQueue((null));
}
let queue2;
if (alternateFiber !== null) {
// alternate fiber實例存在,則需要爲此
queue2 = alternateFiber.updateQueue;
if (queue2 === null) {
queue2 = alternateFiber.updateQueue = createUpdateQueue((null: any));
}
} else {
queue2 = null;
}
queue2 = queue2 !== queue1 ? queue2 : null;
// 如果只存在一個更新隊列
if (queue2 === null) {
insertUpdateIntoQueue(queue1, update);
return;
}
// 如果任意更新隊列爲空,則需要將更新添加至兩個更新隊列
if (queue1.last === null || queue2.last === null) {
insertUpdateIntoQueue(queue1, update);
insertUpdateIntoQueue(queue2, update);
return;
}
// 如果2個更新隊列均非空,則添加更新至第一個隊列,並更新另一個隊列的尾部更新項
insertUpdateIntoQueue(queue1, update);
queue2.last = update;
}
// 處理更新隊列任務,返回新狀態對象
export function processUpdateQueue<State>(
current, workInProgress, queue, instance, props,
renderExpirationTime,
) {
if (current !== null && current.updateQueue === queue) {
// 克隆current fiber以創建work-in-progress fiber
const currentQueue = queue;
queue = workInProgress.updateQueue = {
baseState: currentQueue.baseState,
expirationTime: currentQueue.expirationTime,
first: currentQueue.first,
last: currentQueue.last,
isInitialized: currentQueue.isInitialized,
// These fields are no longer valid because they were already committed. Reset them.
callbackList: null,
hasForceUpdate: false,
};
}
// Reset the remaining expiration time. If we skip over any updates, we'll
// increase this accordingly.
queue.expirationTime = NoWork;
let dontMutatePrevState = true;
let update = queue.first;
let didSkip = false;
while (update !== null) {
const updateExpirationTime = update.expirationTime;
if (updateExpirationTime > renderExpirationTime) {
// 此更新優先級不夠,不處理,跳過
if (queue.expirationTime === NoWork ||
queue.expirationTime > updateExpirationTime
) {
// 重新設置最近未處理更新的到期時間
queue.expirationTime = updateExpirationTime;
}
update = update.next;
continue;
}
// 優先級足夠,處理
let partialState;
if (update.isReplace) {
// 使用replaceState()直接替換狀態對象方式更新時
// 獲取新狀態對象
state = getStateFromUpdate(update, instance, state, props);
// 不需要合併至之前狀態對象,標記爲true
dontMutatePrevState = true;
} else {
// 更新部分狀態方式
// 獲取更新部分狀態時的狀態對象
partialState = getStateFromUpdate(update, instance, state, props);
if (partialState) {
if (dontMutatePrevState) {
// 上一次是替換狀態,所以不能影響state
state = Object.assign({}, state, partialState);
} else {
// 更新部分狀態,直接將新狀態合併至上一次狀態
state = Object.assign(state, partialState);
}
// 重置標記爲false
dontMutatePrevState = false;
}
}
// 強制立即更新
if (update.isForced) {
queue.hasForceUpdate = true;
}
// 添加回調函數
if (update.callback !== null) {
// Append to list of callbacks.
let callbackList = queue.callbackList;
if (callbackList === null) {
callbackList = queue.callbackList = [];
}
callbackList.push(update);
}
// 遍歷下一個更新任務
update = update.next;
}
// 返回最新的狀態對象
return state;
}
更新器(Updater)
調度器協調,調度的任務主要就是執行組件或組件樹更新,而這些任務則具體由更新器(Updater)完成,可以說調度器是在整個應用組件樹層面掌控全局,而更新器則深入到個更具體的每一個組件內部執行。
每一個組件實例化時都會被注入一個更新器,負責協調組件與React核心進程的通信,其職責主要可以概括爲以下幾點:
- 找到組件實例對應的fiber實例;
- 詢問調度器當前組件fiber實例的優先級;
- 將更新推入fiber的更新隊列;
- 根據優先級調度更新任務;
更新器實現見ReactFiberClassComponent模塊:
export default function(
scheduleWork: (fiber: Fiber, expirationTime: ExpirationTime) => void,
computeExpirationForFiber: (fiber: Fiber) => ExpirationTime,
memoizeProps: (workInProgress: Fiber, props: any) => void,
memoizeState: (workInProgress: Fiber, state: any) => void,
) {
// Class component state updater
const updater = {
isMounted,
// 狀態變更,更新入隊列
enqueueSetState(instance, partialState, callback) {
// 獲取fiber
const fiber = ReactInstanceMap.get(instance);
const expirationTime = computeExpirationForFiber(fiber);
// 創建更新任務
const update = {
expirationTime,
partialState,
callback,
isReplace: false,
isForced: false,
nextCallback: null,
next: null,
};
// 添加更新任務至fiber
insertUpdateIntoFiber(fiber, update);
// 調用調度器API以調度fiber任務
scheduleWork(fiber, expirationTime);
},
// 替換狀態時
enqueueReplaceState(instance, state, callback) {
const fiber = ReactInstanceMap.get(instance);
const expirationTime = computeExpirationForFiber(fiber);
const update = {
expirationTime,
partialState: state,
callback,
isReplace: true,
isForced: false,
nextCallback: null,
next: null,
};
// 添加更新任務至fiber
insertUpdateIntoFiber(fiber, update);
scheduleWork(fiber, expirationTime);
},
// 強制更新
enqueueForceUpdate(instance, callback) {
const fiber = ReactInstanceMap.get(instance);
const expirationTime = computeExpirationForFiber(fiber);
const update = {
expirationTime,
partialState: null,
callback,
isReplace: false,
isForced: true,
nextCallback: null,
next: null,
};
insertUpdateIntoFiber(fiber, update);
scheduleWork(fiber, expirationTime);
},
};
// 調用組件實例生命週期方法並調用更新器API
function callComponentWillReceiveProps(
workInProgress, instance, newProps, newContext
) {
const oldState = instance.state;
instance.componentWillReceiveProps(newProps, newContext);
if (instance.state !== oldState) {
// 調用更新器入隊列方法
updater.enqueueReplaceState(instance, instance.state, null);
}
}
// 設置Class組件實例的更新器和fiber
function adoptClassInstance(workInProgress, instance): {
// 設置更新器
instance.updater = updater;
workInProgress.stateNode = instance;
// 設置fiber
ReactInstanceMap.set(instance, workInProgress);
}
// 實例化Class組件實例
function constructClassInstance(workInProgress, props) {
const ctor = workInProgress.type;
const unmaskedContext = getUnmaskedContext(workInProgress);
const needsContext = isContextConsumer(workInProgress);
const context = needsContext
? getMaskedContext(workInProgress, unmaskedContext)
: emptyObject;
// 實例化組件類型
const instance = new ctor(props, context);
// 設置Class實例的更新器和fiber
adoptClassInstance(workInProgress, instance);
return instance;
}
// 掛載組件實例
function mountClassInstance(
workInProgress, renderExpirationTime) {
if (typeof instance.componentWillMount === 'function') {
callComponentWillMount(workInProgress, instance);
}
}
// 更新組件實例
function updateClassInstance(
current, workInProgress, renderExpirationTime
) {
// 組件實例
const instance = workInProgress.stateNode;
// 原Props或新Props
const oldProps = workInProgress.memoizedProps;
let newProps = workInProgress.pendingProps;
if (!newProps) {
// 沒有新Props則直接使用原Props
newProps = oldProps;
}
if (typeof instance.componentWillReceiveProps === 'function' &&
(oldProps !== newProps)) {
// 調用方法進行更新器相關處理
callComponentWillReceiveProps(
workInProgress, instance, newProps
);
}
// 根據原狀態對象和更新隊列計算得到新狀態對象
const oldState = workInProgress.memoizedState;
let newState;
if (workInProgress.updateQueue !== null) {
// 處理更新隊列更新,計算得到新State對象
newState = processUpdateQueue(
current,
workInProgress,
workInProgress.updateQueue,
instance,
newProps,
renderExpirationTime,
);
} else {
newState = oldState;
}
// 檢查是否需要更新組件
const shouldUpdate = checkShouldComponentUpdate(...);
if (shouldUpdate) {
if (typeof instance.componentWillUpdate === 'function') {
instance.componentWillUpdate(newProps, newState, newContext);
}
}
// 調用生命週期方法
...
return shouldUpdate;
}
return {
adoptClassInstance,
constructClassInstance,
mountClassInstance,
updateClassInstance
};
}
主要實現以下幾個功能:
-
初始化組件實例併爲其設置fibre實例和更新器;
-
初始化或更新組件實例,根據更新隊列計算得到新狀態等;
-
調用組件實例生命週期方法,並且調用更新器API更新fiber實例等,如更新組件實例調用的
callComponentWillReceiveProps
方法,該方法調用組件實例的componentWillReceiveProps
生命週期方法,並調用更新器updater.enqueueReplaceState
方法,更新fiber實例,並將更新添加至更新隊列:// 調用組件實例生命週期方法並調用更新器API function callComponentWillReceiveProps( workInProgress, instance, newProps, newContext ) { const oldState = instance.state; instance.componentWillReceiveProps(newProps, newContext); if (instance.state !== oldState) { // 調用更新器入隊列方法 updater.enqueueReplaceState(instance, instance.state, null); } }
另外需要重點關注的是insertUpdateIntoFiber
方法,該方法實現將更新任務添加至組件fiber實例,內部會處理將任務添加至fiber更新隊列,源碼見上文更新隊列中介紹的ReactFiberUpdateQueue模塊,最終還是調用insertUpdateIntoQueue
。
獲取fiber實例
獲取fiber實例比較簡單,fiber實例通過ReactInstanceMap
模塊提供的API進行維護:
export function get(key) {
return key._reactInternalFiber;
}
export function set(key, value) {
key._reactInternalFiber = value;
}
使用節點上的_reactInternalFiber
屬性維護fiber實例,調用get
方法即可獲取。
獲取優先級
fiber實例的優先級是由調度器控制,所以需要詢問調度器關於當前fiber實例的優先級,調度器提供computeExpirationForFiber
獲取特定fiber實例的優先級,即獲取特點fiber實例的到期時間(expirationTime),方法具體實現見調度器與優先級章節。
將更新任務添加至更新隊列
組件狀態變更時,將對應的組件更新任務劃分優先級並根據優先級從高到低依次推入fiber實例的更新隊列,諸如使用setState
方法觸發的更新任務通常是添加至更新隊列尾部。
調度器完成切分任務爲任務單元后,將使用performUnitOfWork
方法開始處理任務單元,然後按調用組件的更新器(實現見上文介紹)相關API,按優先級將任務單元添加至fiber實例的更新隊列:
-
從work-in-progress的alternate屬性獲取當前穩定fiber,然後調用
beginWork
開始處理更新;// 處理任務單元 function performUnitOfWork(workInProgress: Fiber): Fiber | null { // 當前最新版本fiber實例使用fiber的alternate屬性獲取 const current = workInProgress.alternate; // 開始處理,返回子組件fiber實例 let next = beginWork(current, workInProgress, nextRenderExpirationTime); if (next === null) { // 不存在子級fiber,完成單元任務的處理,之後繼續處理下一個任務 next = completeUnitOfWork(workInProgress); } return next; }
-
beginWork
返回傳入fiber實例的子組件fiber實例,,若爲空,則代表此組件樹任務處理完成,否則會在workLoop
方法內迭代調用performUnitOfWork
方法處理:deadline
:是調用requestIdleCallback
API執行任務處理函數時返回的幀時間對象;nextUnitOfWork
:下一個要處理的任務單元;shouldYield
:判斷是否暫停當前任務處理過程;
function workLoop(expirationTime) { // 渲染更新至DOM的到期時間值 小於 調度開始至開始處理此fiber的時間段值 // 說明任務已經過期 if (nextRenderExpirationTime <= mostRecentCurrentTime) { // Flush all expired work, 處理所有已經到期的更新 while (nextUnitOfWork !== null) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } } else { // Flush asynchronous work until the deadline runs out of time. // 依次處理異步更新,直至deadline到達 while (nextUnitOfWork !== null && !shouldYield()) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } } } // 處理異步任務時, 調和器將詢問渲染器是否暫停執行; // 在DOM中,使用requestIdleCallback API實現 function shouldYield() { if (deadline === null) { return false; } if (deadline.timeRemaining() > 1) { // 這一幀幀還有剩餘時間,不需要暫停; // 只有非過期任務可以到達此判斷條件 return false; } deadlineDidExpire = true; return true; }
-
beginWork
方法內根據組件類型調用不同方法,這些方法內調用更新器API將更新添加至更新隊列,具體實現見ReactFiberBeginWork模塊:// 引入更新器模塊 import ReactFiberClassComponent from './ReactFiberClassComponent'; export default function( config, hostContext, hydrationContext, scheduleWork: (fiber: Fiber, expirationTime: ExpirationTime) => void, computeExpirationForFiber: (fiber: Fiber) => ExpirationTime, ) { // 初始化更新器模塊,獲取API const { adoptClassInstance, constructClassInstance, mountClassInstance, updateClassInstance } = ReactFiberClassComponent( scheduleWork, computeExpirationForFiber, memoizeProps, memoizeState ); // beginWork,開始任務處理 function beginWork( current, workInProgress, renderExpirationTime ) { switch (workInProgress.tag) { // 對應不同類型fiber,執行不同處理邏輯 case IndeterminateComponent: ... case FunctionalComponent: return updateFunctionalComponent(current, workInProgress); case ClassComponent: // 更新類組件,返回子級fiber實例 return updateClassComponent( current, workInProgress, renderExpirationTime ); case HostRoot: return updateHostRoot(current, workInProgress, renderExpirationTime); case HostComponent: ... case HostText: return updateHostText(current, workInProgress); case CallHandlerPhase: // This is a restart. Reset the tag to the initial phase. workInProgress.tag = CallComponent; case CallComponent: ... case ReturnComponent: // A return component is just a placeholder, we can just run through the // next one immediately. return null; case HostPortal: ... case Fragment: return updateFragment(current, workInProgress); default:; } } return { beginWork, beginFailedWork }; }
-
引入
ReactFiberClassComponent
更新器相關模塊並初始化獲得API; -
beginWork
方法內根據傳入的work-in-progress的fiber類型(tag)調用不同邏輯處理; -
在邏輯處理裏面會調用更新期API,將更新添加至更新隊列;
-
以
ClassComponent
爲例,將調用updateClassComponent
方法:-
判斷若第一次則初始化並掛載組件實例,否則調用
updateClassInstance
方法更新組件實例; -
最後調用
finishClassComponent
方法,調和處理其子組件並返回其子級fiber實例;// 更新類組件 function updateClassComponent( current, workInProgress, renderExpirationTime ) { let shouldUpdate; if (current === null) { if (!workInProgress.stateNode) { // fiber沒有組件實例時需要初始化組件實例 constructClassInstance(workInProgress, workInProgress.pendingProps); // 掛載組件實例 mountClassInstance(workInProgress, renderExpirationTime); // 默認需要更新 shouldUpdate = true; } } else { // 處理實例更新並返回是否需要更新組件 shouldUpdate = updateClassInstance( current, workInProgress, renderExpirationTime, ); } // 更新完成後,返回子組件fiber實例 return finishClassComponent( current, workInProgress, shouldUpdate, hasContext ); } // 類組件更新完成 function finishClassComponent( current, workInProgress, shouldUpdate, hasContext ) { if (!shouldUpdate) { // 明確設置不需要更新時,不處理更新, // 如shouldCOmponentUpdate方法return false return bailoutOnAlreadyFinishedWork(current, workInProgress); } const instance = workInProgress.stateNode; // 重新渲染 ReactCurrentOwner.current = workInProgress; // 返回組件子組件樹等內容 let nextChildren = instance.render(); // 調和子組件樹,將迭代處理每一個組件 // 函數內將調用ReactChildFiber模塊提供的API reconcileChildren(current, workInProgress, nextChildren); // 返回子組件fiber實例 return workInProgress.child; }
-
-
調度更新任務
上一節更新器已經能按照優先級將更新添加至更新隊列,那麼如何調度執行更新任務呢?
在更新器實現ReactFiberClassComponent模塊中,在enqueueSetState
,enqueueReplaceState
和enqueueForceUpdate
入隊列方法中,均會調用如下方法:
insertUpdateIntoFiber(fiber, update);
scheduleWork(fiber, expirationTime);
insertUpdateIntoFiber
:將更新添加至fiber實例,最終會添加至更新隊列;scheduleWork
:調度任務,傳入fiber實例和任務到期時間;
渲染與調和
在調和階段,不涉及任何DOM處理,在處理完更新後,需要渲染模塊將更新渲染至DOM,這也是React應用中虛擬DOM(Virtual DOM)的概念,即所有的更新計算都基於虛擬DOM,計算完後纔將優化後的更新渲染至真實DOM。Fiber使用requestIdleCallback
API更高效的執行渲染更新的任務,實現任務的切分。
源碼簡單分析
本小節針對React渲染模塊及調和算法模塊代碼層關係做簡要探討,不感興趣可以跳過此劫(節)。
react-dom渲染模塊
在項目中,如果要將應用渲染至頁面,通常會有如下代碼:
import ReactDOM from 'react-dom';
import App form './App'; // 應用根組件
ReactDOM.render(
<App>,
document.querySelector('#App') // 應用掛載容器DOM
);
react-dom
模塊就是適用於瀏覽器端渲染React應用的渲染方案,ReactDOM模塊源碼結構如:
const ReactDOM = {
render(
element: React$Element<any>, // React元素,通常是項目根組件
container: DOMContainer, // React應用掛載的DOM容器
callback: ?Function, // 回調函數
) {
return renderSubtreeIntoContainer(
null,
element,
container,
false,
callback,
);
}
};
常用的渲染組件至DOM的render
方法如上,調用renderSubtreeIntoContainer
方法,渲染組件的子組件樹:
// 渲染組件的子組件樹至父容器
function renderSubtreeIntoContainer(
parentComponent: ?React$Component<any, any>,
children: ReactNodeList,
container: DOMContainer,
forceHydrate: boolean,
callback: ?Function,
) {
let root = container._reactRootContainer;
if (!root) {
// 初次渲染時初始化
// 創建react根容器
const newRoot = DOMRenderer.createContainer(container, shouldHydrate);
// 緩存react根容器至DOM容器的reactRootContainer屬性
root = container._reactRootContainer = newRoot;
// 初始化容器相關
// Initial mount should not be batched.
DOMRenderer.unbatchedUpdates(() => {
DOMRenderer.updateContainer(children, newRoot, parentComponent, callback);
});
} else {
// 如果不是初次渲染則直接更新容器
DOMRenderer.updateContainer(children, root, parentComponent, callback);
}
// 返回根容器fiber樹的根fiber實例
return DOMRenderer.getPublicRootInstance(root);
}
DOM渲染器對象
DOMRenderer
是調用調和算法返回的DOM渲染器對象,在此處會傳入渲染模塊的渲染UI操作API,如:
// 調用調和算法方法
const DOMRenderer = ReactFiberReconciler(
// 傳遞至調和算法中的渲染UI(react-dom模塊即DOM)
// 實際操作API
{
getPublicInstance(instance) {
return instance;
},
createInstance(
type: string,
props: Props,
rootContainerInstance: Container,
hostContext: HostContext,
internalInstanceHandle: Object,
) {
// 創建DOM元素
const domElement = createElement(
type,
props,
rootContainerInstance,
parentNamespace,
);
precacheFiberNode(internalInstanceHandle, domElement);
updateFiberProps(domElement, props);
return domElement;
},
now: ReactDOMFrameScheduling.now,
mutation: {
// 提交渲染
commitMount(
domElement: Instance,
type: string,
newProps: Props,
internalInstanceHandle: Object,
) {
((domElement: any):
| HTMLButtonElement
| HTMLInputElement
| HTMLSelectElement
| HTMLTextAreaElement).focus();
},
// 提交更新
commitUpdate(
domElement: Instance,
updatePayload: Array<mixed>,
type: string,
oldProps: Props,
newProps: Props,
internalInstanceHandle: Object,
) {
// 更新屬性
updateFiberProps(domElement, newProps);
// 對DOM節點進行Diff算法分析
updateProperties(domElement, updatePayload, type, oldProps, newProps);
},
// 清空文本內容
resetTextContent(domElement: Instance): void {
domElement.textContent = '';
},
// 添加爲子級
appendChild(
parentInstance: Instance,
child: Instance | TextInstance,
): void {
parentInstance.appendChild(child);
}
...
}
});
ReactDOMFrameScheduling.now源碼見Github。
在任務完成時將執行createInstance
方法,然後調用createElement
創建DOM元素並添加至文檔。
調和算法入口
調和算法入口:
import ReactFiberScheduler from './ReactFiberScheduler';
import {insertUpdateIntoFiber} from './ReactFiberUpdateQueue';
export default function Reconciler(
// all parameters as config object
// 下文用到的config參數即從此處傳入
getPublicInstance,
createInstance,
...
) {
// 生成調度器API
var {
computeAsyncExpiration, computeExpirationForFiber, scheduleWork,
batchedUpdates, unbatchedUpdates, flushSync, deferredUpdates,
} = ReactFiberScheduler(config);
return {
// 創建容器
createContainer(containerInfo, hydrate: boolean) {
// 創建根fiber實例
return createFiberRoot(containerInfo, hydrate);
},
// 更新容器內容
updateContainer(
element: ReactNodeList,
container: OpaqueRoot,
parentComponent: ?React$Component<any, any>,
callback: ?Function,
): void {
const current = container.current;
...
// 更新
scheduleTopLevelUpdate(current, element, callback);
},
...
// 獲取容器fiber樹的根fiber實例
getPublicRootInstance (container) {
// 獲取fiber實例
const containerFiber = container.current;
if (!containerFiber.child) {
return null;
}
switch (containerFiber.child.tag) {
case HostComponent:
return getPublicInstance(containerFiber.child.stateNode);
default:
return containerFiber.child.stateNode;
}
},
unbatchedUpdates
}
}
在react-dom
渲染模塊調用createContainer
創建容器和根fiber實例,FiberRoot對象,調用updateContainer
方法更新容器內容。
開始更新
// 更新
function scheduleTopLevelUpdate(
current: Fiber,
element: ReactNodeList,
callback: ?Function,
) {
callback = callback === undefined ? null : callback;
const update = {
expirationTime,
partialState: {element},
callback,
isReplace: false,
isForced: false,
nextCallback: null,
next: null,
};
// 更新fiber實例
insertUpdateIntoFiber(current, update);
// 執行任務
scheduleWork(current, expirationTime);
}
處理更新
調用scheduleWork
方法處理更新任務,實現見上文,源碼。
提交更新
處理完更新後需要確認提交更新至渲染模塊,然後渲染模塊才能將更新渲染至DOM。
import ReactFiberCommitWork from './ReactFiberCommitWork';
const {
commitResetTextContent,
commitPlacement,
commitDeletion,
commitWork,
commitLifeCycles,
commitAttachRef,
commitDetachRef,
} = ReactFiberCommitWork(config, captureError);
function commitRoot(finishedWork) {
...
commitAllHostEffects();
}
// 循環執行提交更新
function commitAllHostEffects() {
while (nextEffect !== null) {
let primaryEffectTag =
effectTag & ~(Callback | Err | ContentReset | Ref | PerformedWork);
switch (primaryEffectTag) {
case Placement: {
commitPlacement(nextEffect);
nextEffect.effectTag &= ~Placement;
break;
}
case PlacementAndUpdate: {
// Placement
commitPlacement(nextEffect);
nextEffect.effectTag &= ~Placement;
// Update
const current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
case Update: {
const current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
case Deletion: {
isUnmounting = true;
commitDeletion(nextEffect);
isUnmounting = false;
break;
}
}
nextEffect = nextEffect.nextEffect;
}
}
// Flush sync work.
let finishedWork = root.finishedWork;
if (finishedWork !== null) {
// This root is already complete. We can commit it.
root.finishedWork = null;
root.remainingExpirationTime = commitRoot(finishedWork);
}
提交更新是最後確認更新組件的階段,主要邏輯如下:
export default function (mutation, ...) {
const {
commitMount,
commitUpdate,
resetTextContent,
commitTextUpdate,
appendChild,
appendChildToContainer,
insertBefore,
insertInContainerBefore,
removeChild,
removeChildFromContainer,
} = mutation;
function commitWork(current: Fiber | null, finishedWork: Fiber): void {
switch (finishedWork.tag) {
case ClassComponent: {
return;
}
case HostComponent: {
const instance: I = finishedWork.stateNode;
if (instance != null) {
// Commit the work prepared earlier.
const newProps = finishedWork.memoizedProps;
// For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
const oldProps = current !== null ? current.memoizedProps : newProps;
const type = finishedWork.type;
// TODO: Type the updateQueue to be specific to host components.
const updatePayload = finishedWork.updateQueue:;
finishedWork.updateQueue = null;
if (updatePayload !== null) {
commitUpdate(
instance,
updatePayload,
type,
oldProps,
newProps,
finishedWork,
);
}
}
return;
}
case HostText: {
const textInstance = finishedWork.stateNode;
const newText = finishedWork.memoizedProps;
// For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
const oldText: string =
current !== null ? current.memoizedProps : newText;
commitTextUpdate(textInstance, oldText, newText);
return;
}
case HostRoot: {
return;
}
default: {
}
}
}
}