마운트와 업데이트라는 두 가지 상황이 있으므로 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 함수는 콜백 함수를 호출하여 값을 계산하고 반환합니다. 값과 deps를 Hook.memoizedState.
mountWorkInProgressHook를 사용하여 후크 객체를 생성합니다.
nextDeps에 deps를 저장합니다.
nextCreate()를 호출하여 nextValue를 얻습니다. 개발 환경에서는 두 번 호출하세요.
hook.memoizedState에 nextValue와 nextDeps를 저장하고 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