useMemo의 소스 코드:

Patricia Arquette
풀어 주다: 2024-10-04 18:21:31
원래의
963명이 탐색했습니다.

The source code of useMemo:

마운트와 업데이트라는 두 가지 상황이 있으므로 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 함수는 콜백 함수를 호출하여 값을 계산하고 반환합니다. 값과 deps를 Hook.memoizedState에 저장하세요.

  1. mountWorkInProgressHook을 사용하여 후크 개체를 생성하세요.

  2. nextDeps에 deps를 저장하세요.

  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 배열이 비어 있는 경우(nextDeps !== null), 렌더링할 때마다 콜백 함수를 호출하고 새 값을 반환합니다.
  3. deps 배열이 비어 있지 않으면 (areHookInputsEqual(nextDeps, prevDeps))인 경우 deps가 변경되었는지 여부를 판단합니다. 변경되지 않은 경우 이전 값을 반환합니다. return prevState[0];.

위 내용은 useMemo의 소스 코드:의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!