首頁 > web前端 > js教程 > 主體

useMemo的原始碼:

Patricia Arquette
發布: 2024-10-04 18:21:31
原創
962 人瀏覽過

The source code of useMemo:

有兩種情況:mount和update,所以useMemo有兩種實作:mountMemoupdateMemo

  • mountMemo原始碼:

function mountMemo<T>(
  nextCreate: () => T,
  deps: Array<mixed> | 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 中。

  1. 使用 mountWorkInProgressHook 建立鉤子物件。

  2. 將 deps 保存在 nextDeps 中。

  3. 呼叫nextCreate()取得nextValue。如果在開發環境中,請呼叫兩次。

  4. 將 nextValue 和 nextDeps 保存在 hook.memoizedState 中並傳回 nextValue。

  • updateMemo的原始碼:

function updateMemo<T>(
  nextCreate: () => T,
  deps: Array<mixed> | 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<mixed> | 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 將傳回舊值。

  1. 取得新的鉤子物件:hook = updateWorkInProgressHook();
  2. 如果 deps 陣列為空 if (nextDeps !== null),則每次渲染時呼叫回呼函數並傳回新值。
  3. 如果deps數組不為空,則判斷deps是否發生變化 if (areHookInputsEqual(nextDeps, prevDeps))。如果沒有改變,則傳回舊值 return prevState[0];.

以上是useMemo的原始碼:的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!