有兩種情況:掛載和更新,所以useMemo有兩種實作:mountMemo和updateMemo。
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建立鉤子物件。
將 deps 保存在 nextDeps 中。
呼叫nextCreate()取得nextValue。如果在開發環境中,則呼叫兩次。
將nextValue和nextDeps保存在hook.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