Skip to content
On this page
js
function render(element, container, callback) {
	// ...
	return legacyRenderSubtreeIntoContainer(null, element,container, false, callback)
}

function legacyRenderSubtreeIntoContainer(
	parentComponent, children, container, forceHydrate, callback
) {
	var root = container._reactRootContainer; // 可以在DOM元素查看 React 应用
  var fiberRoot;
  if (!root) {
		// 创建 FiberRootNode
	  root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
    fiberRoot = root;
    // 调用callback
    if (typeof callback === 'function') {
      var originalCallback = callback;
      callback = function () {
        var instance = getPublicRootInstance(fiberRoot);
        originalCallback.call(instance);
      };
    }
    // 进入调度
    flushSync(function () {
      updateContainer(children, fiberRoot, parentComponent, callback);
    });
	}
}

function updateContainer(
	element, container, parentComponent, callback
) {
	const current = container.current; // 根节点的 current FiberNode
	const eventTime = requestEventTime(); // 任务时间
	// 当前优先级,同步更新为 1
	const lane = requestUpdateLane(current); 
	// context 上下文
  const context = getContextForSubtree(parentComponent);
  if (container.context === null) {
    container.context = context;
  } else {
    container.pendingContext = context;
  }
  // 创建 update
  const update = createUpdate(eventTime, lane); 
	update.payload = {element};
	// 添加更新队列
	enqueueUpdate(current, update);
	//  调度更新
	scheduleUpdateOnFiber(current, lane, eventTime);
}

function enqueueUpdate(fiber, update, lane){
	// 将更新对象添加到fiber的更新队列
	const updateQueue = fiber.updateQueue;
  if (updateQueue === null) {
    return;
  }
	const sharedQueue = updateQueue.shared;
  if (isInterleavedUpdate(fiber)) {
    const interleaved = sharedQueue.interleaved;
    if (interleaved === null) {
      update.next = update;
      pushInterleavedQueue(sharedQueue);
    } else {
      update.next = interleaved.next;
      interleaved.next = update;
    }
    sharedQueue.interleaved = update;
  } else {
	  // 加入 pending 这个环状链表
    var pending = sharedQueue.pending;
    if (pending === null) {
      update.next = update;
    } else {
      update.next = pending.next;
      pending.next = update;
    }

    sharedQueue.pending = update;
  }
}

function scheduleUpdateOnFiber(fiber, lane, eventTime) {
	// 找到 上面生成的 FiberRootNode
	const root = markUpdateLaneFromFiberToRoot(fiber, lane);
	if (root === null) {
		return null;
	}
	markRootUpdated(root, lane, eventTime);
	// ..
	if (lane === SyncLane) {
		// 同步更新
		// render 阶段入口
		performSyncWorkOnRoot(root);
	} else {
		// 并发更新模式
		ensureRootIsScheduled(root, eventTime);
	}
}