Skip to content
On this page

对比 Vue 通过 defineProperty 或者 Proxy ,当数据改变的时候调用更新

React 通过创建 Update 对象(dispatchAction) ,在 render 阶段(performSyncWorkOnRoot),记录 更新内容,最终通过 commit 阶段(commitRoot) 进行更新

useState 为例子,在 触发更新 setState ,会调用 `dispatchAction

js
function dispatchAction(fiber, queue, action) {
	// fiber 当前 function fiber节点
	// action 传入的新状态state
	// 创建的 update 对象
	var lane = requestUpdateLane(fiber);
	var update = {
    lane: lane,
    action: action,
    hasEagerState: false,
    eagerState: null,
    next: null
  };
  //...
  const eventTime = requestEventTime();
  const root = scheduleUpdateOnFiber(fiber, lane, eventTime)
}

function scheduleUpdateOnFiber() {
	// 通过 fiber 向上递归 找到当前应用的 FiberRootNode
	let root = markUpdateLaneFromFiberToRoot(fiber, lane);
	//...
	ensureRootIsScheduled(root, eventTime);
	return root
}

function ensureRootIsScheduled(root, eventTime) {
	// 核心代码
	let newCallbackNode;
	if (newCallbackPriority === SyncLanePriority) {
		// 任务已经过期,需要同步执行render阶段
		newCallbackNode = scheduleSyncCallback(
			performSyncWorkOnRoot.bind(null, root),
		);
	} else {
		// 根据任务优先级异步执行render阶段
		const schedulerPriorityLevel = lanePriorityToSchedulerPriority(
			newCallbackPriority,
		);
		newCallbackNode = scheduleCallback(
			schedulerPriorityLevel,
			performConcurrentWorkOnRoot.bind(null, root),
		);
	}
}

其中,scheduleCallbackscheduleSyncCallback会调用 Scheduler 提供的调度方法根据优先级调度回调函数执行。 回调函数也就是 performSyncWorkOnRootperformConcurrentWorkOnRoot