React18源码-初次流程渲染浅析(一)
文章目录
调试代码
const App = function () {
//...
};
const domNode = document.getElementById("root");
const root = ReactDOM.createRoot(domNode);
root.render(<App />);ReactDOM.createRoot()
一系列对象的初始化和事件初始化
function createRoot(container, options) {
//...
var root = createContainer(
container,
ConcurrentRoot,
null,
isStrictMode,
concurrentUpdatesByDefaultOverride,
identifierPrefix,
onRecoverableError
);
markContainerAsRoot(root.current, container);
//...
listenToAllSupportedEvents(rootContainerElement);
return new ReactDOMRoot(root);
}1.1 createContainer()
本质就是调用createFiberRoot():
- 创建
root=new FiberRootNode()对象(一个非常普通的对象具有一些特定的属性) - 创建
uninitializedFiber=new FiberNode()对象(一个非常普通的对象具有一些特定的属性) FiberRootNode和FiberNode相互绑定- 初始化
root对应fiber的state对象,放入fiber.memoizedState中 initializeUpdateQueue():fiber.updateQueue初始化(updateQueue也是一个非常普通的对象具有一些特定的属性)
function createContainer() {
return createFiberRoot(...);
}
function createFiberRoot(...) {
var root = new FiberRootNode(...);
var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
root.current = uninitializedFiber;
uninitializedFiber.stateNode = root;
//...
var initialState = {...};
uninitializedFiber.memoizedState = initialState;
initializeUpdateQueue(uninitializedFiber);
return root;
}
function FiberRootNode(...) {
this.tag = tag;
this.containerInfo = containerInfo;
//...
}
function createHostRootFiber() {
return createFiber(HostRoot, null, null, mode);
}
var createFiber = function (...) {
return new FiberNode(...);
}
function FiberNode(...) {
this.tag = tag;
this.key = key;
//...
}
function initializeUpdateQueue(fiber) {
var queue = {
baseState: fiber.memoizedState,
firstBaseUpdate: null,
lastBaseUpdate: null,
shared: {
pending: null,
lanes: NoLanes,
},
effects: null,
};
fiber.updateQueue = queue;
}1.2 markContainerAsRoot()
root.current为创建的fiber,container为传入的dom
下面这一行本质就是container[xxxx] = root.current(数据绑定)
// markContainerAsRoot(root.current, container);
function markContainerAsRoot(hostRoot, node) {
node[internalContainerInstanceKey] = hostRoot;
}1.3 listenToAllSupportedEvents()
为rootDOM注册所有支持的原生事件监听
由于这一块比较复杂,后面会出一篇文章具体分析listenToAllSupportedEvents,后面完成后再补充链接到这里1.4 new ReactDOMRoot(root)
将新建的FiberRootNode对象放入到this._internalRoot中
function ReactDOMRoot(internalRoot) {
this._internalRoot = internalRoot;
}render()
本质调用的是updateContainer()方法
ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = {
//...
updateContainer(children, root, null, null);
};而updateContainer()方法主要分为:
requestUpdateLane()创建update对应的lanecreateUpdate()创建更新update对象createUpdate()创建更新updateQueue队列enqueueUpdate()将update放入队列中scheduleUpdateOnFiber()处理队列entangleTransitionUpdate()处理Transition lanes的更新
function updateContainer(...) {
var current = container.current;
var lane = requestUpdateLane(current);
//...
var update = createUpdate(eventTime, lane);
update.payload = {
element: element,
};
//...
var root = enqueueUpdate$1(current, update, lane);
if (root !== null) {
scheduleUpdateOnFiber(root, current, lane, eventTime);
entangleTransitions(root, current, lane);
}
return lane;
}requestUpdateLane()
从ReactDOM.createRoot()的分析可以知道,一开始会传入ConcurrentRoot进行fiberRoot的创建,此时mode = ConcurrentMode
function createRoot(container, options) {
var root = createContainer(
container,
ConcurrentRoot,
null,
isStrictMode,
concurrentUpdatesByDefaultOverride,
identifierPrefix,
onRecoverableError
);
}
function createHostRootFiber(tag) {
if (tag === ConcurrentRoot) {
mode = ConcurrentMode;
} else {
mode = NoMode;
}
}由于mode = ConcurrentMode,而且
executionContext未设置值,为 0,即NoContextworkInProgressRootRenderLanes未设置值,为 0,即NoLanesgetCurrentUpdatePriority()未设置值,为 0
因此整体代码会走到getEventPriority(),直接返回DefaultEventPriority=DefaultLane=16
function requestUpdateLane(fiber) {
var mode = fiber.mode;
if ((mode & ConcurrentMode) === NoMode) {
return SyncLane;
} else if (
(executionContext & RenderContext) !== NoContext &&
workInProgressRootRenderLanes !== NoLanes
) {
return pickArbitraryLane(workInProgressRootRenderLanes);
}
var isTransition = requestCurrentTransition() !== NoTransition;
if (isTransition) {
//...
}
var updateLane = getCurrentUpdatePriority();
if (updateLane !== NoLane) {
return updateLane;
}
var eventLane = getCurrentEventPriority();
return eventLane;
}
function getCurrentEventPriority() {
var currentEvent = window.event;
if (currentEvent === undefined) {
return DefaultEventPriority;
}
return getEventPriority(currentEvent.type);
}
function getEventPriority(domEventName) {
// domEventName = "DOMContentLoaded"
switch (domEventName) {
case "cancel":
case "click":
case "close":
case "contextmenu":
case "copy":
case "cut":
//...
default:
return DefaultEventPriority;
}
}createUpdate()创建更新队列
从requestUpdateLane()中得到lane=DefaultLane=16后创建一个update的普通对象
var update = createUpdate(eventTime, lane);function createUpdate(eventTime, lane) {
var update = {
eventTime: eventTime,
lane: lane,
tag: UpdateState,
payload: null,
callback: null,
next: null,
};
return update;
}enqueueUpdate()将 update 放入队列中
整体逻辑比较简单,最终触发
enqueueUpdate():直接将创建的update放入到全局对象concurrentQueues中,并且处理下lanesgetRootForUpdatedFiber():往上寻找到parent,返回HostRoot的node.stateNode
function enqueueUpdate$1(fiber, update, lane) {
var updateQueue = fiber.updateQueue;
var sharedQueue = updateQueue.shared;
//...
return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane);
}
function enqueueConcurrentClassUpdate(fiber, queue, update, lane) {
//...
enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane);
return getRootForUpdatedFiber(fiber);
}function enqueueUpdate(fiber, queue, update, lane) {
concurrentQueues[concurrentQueuesIndex++] = fiber;
concurrentQueues[concurrentQueuesIndex++] = queue;
concurrentQueues[concurrentQueuesIndex++] = update;
concurrentQueues[concurrentQueuesIndex++] = lane;
concurrentlyUpdatedLanes = mergeLanes(concurrentlyUpdatedLanes, lane);
fiber.lanes = mergeLanes(fiber.lanes, lane);
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.lanes = mergeLanes(alternate.lanes, lane);
}
}
function mergeLanes(a, b) {
return a | b;
}function getRootForUpdatedFiber(sourceFiber) {
var node = sourceFiber;
var parent = node.return;
while (parent !== null) {
node = parent;
parent = node.return;
}
return node.tag === HostRoot ? node.stateNode : null;
}scheduleUpdateOnFiber()处理队列
从下面代码可以知道,主要分为:
markStarvedLanesAsExpired():检查root.pendingLanes是否存在lane一直没执行,将它从pendingLanes移动到root.expiredLanesgetNextLanes():获取下一个lanesgetHighestPriorityLane():从lanes中取出优先级最高的lane- 存在新的优先级则取消原来的
existingCallbackNode scheduleCallback$2():新的newCallbackNode的构建下面我们将针对上面几个小点展开详细分析
function ensureRootIsScheduled(root, currentTime) {
var existingCallbackNode = root.callbackNode;
// 2.4.1.1 markStarvedLanesAsExpired饥饿问题
markStarvedLanesAsExpired(root, currentTime);
// 2.4.1.2 getNextLanes = 16
var nextLanes = getNextLanes(
root,
root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes
);
if (nextLanes === NoLanes) {
//...
return;
}
// 2.4.1.3 getHighestPriorityLane = 16
var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it.
var existingCallbackPriority = root.callbackPriority;
// existingCallbackPriority = 0
// newCallbackPriority = DefaultPriority = 16
if (existingCallbackPriority === newCallbackPriority) {
return;
}
if (existingCallbackNode != null) {
cancelCallback$1(existingCallbackNode);
}
var newCallbackNode;
if (newCallbackPriority === SyncLane) {
// ......初次渲染不走这里后续渲染更新再进行分析
} else {
var schedulerPriorityLevel;
switch (lanesToEventPriority(nextLanes)) {
//...
case DefaultEventPriority:
schedulerPriorityLevel = NormalPriority;
break;
}
newCallbackNode = scheduleCallback$2(
schedulerPriorityLevel,
performConcurrentWorkOnRoot.bind(null, root)
);
}
root.callbackPriority = newCallbackPriority;
root.callbackNode = newCallbackNode;
}markRootUpdated()
root.pendingLanes:包含了当前rootFiber树中所有待处理的update的lane(包含所有childFiber的update),可以根据pendingLanes一定范围的取值去拿到当前优先级最高的lanes,然后赋值给renderLanes,后续遍历updateQueue时可以判断当前update是否就是renderLanes的值得到当前优先级最高的update更新对象
注:因为 diff 是从 root 开始的,因此将所有更新信息都同步到 root 可以知道要跳过哪些更新
root.pendingLanes |= updateLane;ensureRootIsScheduled()
markStarvedLanesAsExpired 饥饿问题
低优先级任务一直被高优先级任务打断,检查低优先级任务是否一直堵塞,强制转化为过期任务提高优先级
检查root.pendingLanes是否存在lane一直没执行,将它从pendingLanes移动到root.expiredLanes
从下面代码可以知道,
使用pickArbitraryLaneIndex()获取当前lanes最左边 1 对应的index,比如
lanes=000000011000=>pickArbitraryLaneIndex()=> index=4lane=000000010000
检测这个位置的expirationTime是否存在,如果不存在
computeExpirationTime():根据lane类型,然后加上当前时间+一定的过期时间,比如现在是当前时间是12:40:00,那么它的过期时间就是12:40:00+250,250毫秒后还没执行,证明它进入饥饿状态(除了饥饿,还有死锁、活锁等并发问题)- 如果当前
lane(可以简单认为某一个任务)已经等待很久还没执行(一直被高优先级任务打断),强行将当前lane放入root.expiredLanes 然后从
root.pendingLanes中剔除当前lane:lanes &= ~laneroot.pendingLanes: 等待执行的任务root.expiredLanes: 已经过期的任务,必须马上执行
function markStarvedLanesAsExpired(root, currentTime) {
var pendingLanes = root.pendingLanes;
var expirationTimes = root.expirationTimes;
var lanes = pendingLanes;
while (lanes > 0) {
var index = pickArbitraryLaneIndex(lanes);
var lane = 1 << index;
var expirationTime = expirationTimes[index];
if (expirationTime === NoTimestamp) {
// 找到一个等待的lane,并且不是suspended/pinged,计算一个过期时间
if (
(lane & suspendedLanes) === NoLanes ||
(lane & pingedLanes) !== NoLanes
) {
expirationTimes[index] = computeExpirationTime(lane, currentTime);
}
} else if (expirationTime <= currentTime) {
root.expiredLanes |= lane;
}
lanes &= ~lane;
}
}
function computeExpirationTime(lane, currentTime) {
switch (lane) {
case SyncLane:
//...
return currentTime + 250;
//...
}
}getNextLanes()
由于这一块比较复杂,涉及到大量lanes的计算,后面会出一篇文章具体分析lane,后面完成后再补充链接到这里
getHighestPriorityLane()
lanes的位置是有优先级区分的,高优先级会放在最右边
如下面代码所示,SyncLane占据了最右边的index,当我们想要获取最高优先级lane时,我们就使用lanes & -lanes获取最右边1的位置,通过与SyncLane/InputContinuousHydrationLane/DefaultLane的&运算就可以得出目前执行什么类型的lane
function getHighestPriorityLane(lanes) {
return lanes & -lanes;
}export const SyncLane: Lane = /* */ 0b0000000000000000000000000000001;
export const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000000010;
export const InputContinuousLane: Lane = /* */ 0b0000000000000000000000000000100;
export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000000001000;
export const DefaultLane: Lane = /* */ 0b0000000000000000000000000010000;
const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000000100000;
const TransitionLanes: Lanes = /* */ 0b0000000001111111111111111000000;scheduleCallback()
使用的是scheduler调度器的unstable_scheduleCallback()方法,下面代码虽然很长,但是实际的逻辑是非常简单的,主要集中在几个方面:
taskQueue:存储普通任务的队列timerQueue:存储延迟任务的队列,可以简单理解为需要延迟一定时间才执行的任务,跟普通任务相比较,普通任务是因为当前没有时间给你执行,需要等待,但是延迟任务是需要延迟一定时间才执行
而队列中的优先级是使用newTask.sortIndex = startTime进行区分,同时还具有过期时间expirationTime(防止这个任务一直被其它高优先级抢占资源无法执行,当达到过期时间后,它就可以强行去抢占资源执行)
因此下面的代码中,先处理了startTime和expirationTime(startTime + timeout),然后构建一个新的newTask,放入taskQueue或者timerQueue
- 如果当前新建
newTask属于延迟Task,判断taskQueue是不是没有任务需要执行,如果没有则触发requestHostTimeout()进行倒计时(newTask的延迟时间倒计时),看看能不能把timerQueue的任务挪到taskQueue执行 - 如果当前新建
newTask属于普通Task,加入taskQueue,然后触发requestHostCallback(flushWork)进行任务优先级队列的调度(根据sortIndex执行)
function unstable_scheduleCallback(priorityLevel, callback, options) {
var currentTime = getCurrentTime();
var startTime;
if (typeof options === "object" && options !== null) {
var delay = options.delay;
if (typeof delay === "number" && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
//...
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
var expirationTime = startTime + timeout;
var newTask = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: startTime,
expirationTime: expirationTime,
sortIndex: -1,
};
if (startTime > currentTime) {
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
if (isHostTimeoutScheduled) {
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
}
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}scheduler
将在下一个章节展开分析
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论