跳到主要内容

React DOM 同步刷新

import { disableLegacyMode } from 'shared/ReactFeatureFlags';
import { DiscreteEventPriority } from 'react-reconciler/src/ReactEventPriorities';

import ReactSharedInternals from 'shared/ReactSharedInternals';

import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals';

function flushSyncImpl<R>(fn: () => R): R;
function flushSyncImpl(): void;
function flushSyncImpl<R>(fn?: () => R): R | undefined {
// 上一次过渡
const previousTransition = ReactSharedInternals.T;
// 上一次更新优先级
const previousUpdatePriority =
ReactDOMSharedInternals.p; /* ReactDOMCurrentUpdatePriority */

try {
ReactSharedInternals.T = null;
ReactDOMSharedInternals.p /* ReactDOMCurrentUpdatePriority */ =
DiscreteEventPriority;
if (fn) {
return fn();
} else {
return undefined;
}
} finally {
ReactSharedInternals.T = previousTransition;
ReactDOMSharedInternals.p /* ReactDOMCurrentUpdatePriority */ =
previousUpdatePriority;
const wasInRender =
ReactDOMSharedInternals.d /* ReactDOMCurrentDispatcher */
.f(); /* flushSyncWork */
if (__DEV__) {
if (wasInRender) {
console.error(
'flushSync was called from inside a lifecycle method. React cannot ' +
'flush when React is already rendering. Consider moving this call to ' +
'a scheduler task or micro task.',
);
}
}
}
}

function flushSyncErrorInBuildsThatSupportLegacyMode<R>(fn: () => R): R;
function flushSyncErrorInBuildsThatSupportLegacyMode(): void;
function flushSyncErrorInBuildsThatSupportLegacyMode() {
throw new Error(
'Expected this build of React to not support legacy mode but it does. This is a bug in React.',
);
}

export const flushSync: typeof flushSyncImpl = disableLegacyMode
? flushSyncImpl
: flushSyncErrorInBuildsThatSupportLegacyMode;