You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// react/packages/react-reconciler/src/ReactFiberHooks.jsfunctionmountCallback<T>(callback: T, deps: Array<mixed> | void | null): T {consthook=mountWorkInProgressHook();constnextDeps=deps===undefined ? null : deps;hook.memoizedState=[callback,nextDeps];returncallback;}functionupdateCallback<T>(callback: T, deps: Array<mixed> | void | null): T {consthook=updateWorkInProgressHook();constnextDeps=deps===undefined ? null : deps;constprevState=hook.memoizedState;if(prevState!==null){if(nextDeps!==null){constprevDeps: Array<mixed> | null = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {returnprevState[0];}}}hook.memoizedState=[callback,nextDeps];returncallback;}functionareHookInputsEqual(nextDeps: Array<mixed>,
prevDeps: Array<mixed> | null,
) {if(__DEV__){if(ignorePreviousDependencies){// Only true when this component is being hot reloaded.returnfalse;}}if(prevDeps===null){if(__DEV__){warning(false,'%s received a final argument during this render, but not during '+'the previous render. Even though the final argument is optional, '+'its type cannot change between renders.',currentHookNameInDev,);}returnfalse;}if(__DEV__){// Don't bother comparing lengths in prod because these arrays should be// passed inline.if(nextDeps.length!==prevDeps.length){warning(false,'The final argument passed to %s changed size between renders. The '+'order and size of this array must remain constant.\n\n'+'Previous: %s\n'+'Incoming: %s',currentHookNameInDev,`[${prevDeps.join(', ')}]`,`[${nextDeps.join(', ')}]`,);}}for(leti=0;i<prevDeps.length&&i<nextDeps.length;i++){if(is(nextDeps[i],prevDeps[i])){continue;}returnfalse;}returntrue;}
react 中 hooks 依赖项比较策略
源代码文件路径位置:
react/packages/react-reconciler/src/ReactFiberHooks.js
本文 以
useCallback
为例进行讲解,useMemo
原理也是一样的FC(funcitonal component) 中
useCallback
初始化调用mountCallback
,更新调用updateCallback
以下列出部分主要代码:
我们主要观察
updateCallback
中的代码,当deps
没有发生变化时,从hooks.memoizedState
获取缓存的函数,当deps
发生变化时,返回callback
新函数。而比较deps
是否发生变化在areHookInputsEqual
中,迭代deps
依赖数组,通过is
(其实就是 Object.is 的 polyfill) 函数来判断是否数组的每一项是否发生变化。The text was updated successfully, but these errors were encountered: