マウントと更新の 2 種類の状況があるため、useMemo には mountMemo と updateMemo の 2 つの実装があります。
function mountMemo( nextCreate: () => T, deps: Array | void | null, ): T { const hook = mountWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; const nextValue = nextCreate(); if (shouldDoubleInvokeUserFnsInHooksDEV) { setIsStrictModeForDevtools(true); nextCreate(); setIsStrictModeForDevtools(false); } hook.memoizedState = [nextValue, nextDeps]; return nextValue; }
説明:
マウントフェーズでは、useMemo 関数がコールバック関数を呼び出して値を計算して返します。値を保存し、hook.memoizedState.
mountWorkInProgressHook を使用してフック オブジェクトを作成します。
nextDeps に Deps を保存します。
nextCreate() を呼び出して nextValue を取得します。開発環境の場合は、2 回呼び出します。
nextValue と nextDeps をフック.memoizedState に保存し、nextValue.
function updateMemo( nextCreate: () => T, deps: Array | void | null, ): T { const hook = updateWorkInProgressHook(); const nextDeps = deps === undefined ? null : deps; const prevState = hook.memoizedState; // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { const prevDeps: Array | null = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } const nextValue = nextCreate(); if (shouldDoubleInvokeUserFnsInHooksDEV) { setIsStrictModeForDevtools(true); nextCreate(); setIsStrictModeForDevtools(false); } hook.memoizedState = [nextValue, nextDeps]; return nextValue; }
説明:
更新フェーズでは、React は deps が変更されたかどうかを判断し、変更された場合、React はコールバックを実行して新しい値を取得して戻ります。変更しない場合、React は古い値を返します。
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3