跳到主要内容

React DOM update batching

一、作用

二、批量更新

备注
export function batchedUpdates(fn, a, b) {
if (isInsideEventHandler) {
// If we are currently inside another batch, we need to wait until it
// fully completes before restoring state.
// 如果我们当前正处于另一个批处理中,则需要等到其完全完成后才能恢复状态。
return fn(a, b);
}
isInsideEventHandler = true;
try {
return batchedUpdatesImpl(fn, a, b);
} finally {
isInsideEventHandler = false;
finishEventHandler();
}
}

三、离散更新

备注
// TODO: Replace with flushSync
// 待办事项:替换为 flushSync
export function discreteUpdates(fn, a, b, c, d) {
return discreteUpdatesImpl(fn, a, b, c, d);
}

四、变量

1. 是否在事件处理程序中

// Used as a way to call batchedUpdates when we don't have a reference to
// the renderer. Such as when we're dispatching events or if third party
// libraries need to call batchedUpdates. Eventually, this API will go away when
// everything is batched by default. We'll then have a similar API to opt-out of
// scheduled work and instead do synchronous work.

// 当我们没有渲染器的引用时,用作调用 batchedUpdates 的一种方式。例如,当我们分发事件或
// 第三方库需要调用 batchedUpdates 时。最终,当一切操作默认都是批处理时,这个 API 将被
// 移除。到那时,我们将有一个类似的 API 用于选择退出调度的工作,而改为执行同步工作。

let isInsideEventHandler = false;

五、工具

1. 完成事件处理程序

备注
function finishEventHandler() {
// Here we wait until all updates have propagated, which is important
// when using controlled components within layers:
// 在这里我们等待所有更新传播完成,这一点很重要。尤其是在层内使用受控组件时:
// https://github.com/facebook/react/issues/1698
// Then we restore state of any controlled component.
// 然后我们恢复任何受控组件的状态。
const controlledComponentsHavePendingUpdates = needsStateRestore();
if (controlledComponentsHavePendingUpdates) {
// If a controlled event was fired, we may need to restore the state of
// the DOM node back to the controlled value. This is necessary when React
// bails out of the update without touching the DOM.
// TODO: Restore state in the microtask, after the discrete updates flush,
// instead of early flushing them here.
// @TODO Should move to flushSyncWork once legacy mode is removed but since this flushSync
// flushes passive effects we can't do this yet.

// 如果触发了受控事件,我们可能需要将 DOM 节点的状态恢复到受控值。当 React 在不操
// 作 DOM 的情况下退出更新时,这是必要的。
// TODO: 在微任务中恢复状态,在离散更新刷新之后,而不是在这里提前刷新它们。
// @TODO 一旦移除旧模式应该移到 flushSyncWork,但由于这个 flushSync 会刷新被动
// 效果,我们暂时不能这么做。
flushSyncWork();
restoreStateIfNeeded();
}
}