认识
2023年06月10日
处理策略
hooks
对象本质上是主要以三种处理策略存在 React
中:
ContextOnlyDispatcher
ContextOnlyDispatcher 第一种形态是防止开发者在函数组件外部调用hooks
,所以第一种就是报错形态,只要开发者调用了这个形态下的 hooks
,就会抛出异常。
/react/packages/react-reconciler/src/ReactFiberHooks.new.js
export const ContextOnlyDispatcher: Dispatcher = {
readContext,
useCallback: throwInvalidHookError,
useContext: throwInvalidHookError,
useEffect: throwInvalidHookError,
useImperativeHandle: throwInvalidHookError,
useLayoutEffect: throwInvalidHookError,
useMemo: throwInvalidHookError,
useReducer: throwInvalidHookError,
useRef: throwInvalidHookError,
useState: throwInvalidHookError,
useDebugValue: throwInvalidHookError,
useDeferredValue: throwInvalidHookError,
useTransition: throwInvalidHookError,
useMutableSource: throwInvalidHookError,
useOpaqueIdentifier: throwInvalidHookError,
unstable_isNewReconciler: enableNewReconciler,
};
HooksDispatcherOnMount
HooksDispatcherOnMount 第二种形态是函数组件初始化 mount
,因为之前讲过 hooks
是函数组件和对应 fiber
桥梁,这个时候的 hooks
作用就是建立这个桥梁,初次建立其 hooks
与 fiber
之间的关系。
/react/packages/react-reconciler/src/ReactFiberHooks.new.js
const HooksDispatcherOnMount: Dispatcher = {
readContext,
useCallback: mountCallback,
useContext: readContext,
useEffect: mountEffect,
useImperativeHandle: mountImperativeHandle,
useLayoutEffect: mountLayoutEffect,
useMemo: mountMemo,
useReducer: mountReducer,
useRef: mountRef,
useState: mountState,
useDebugValue: mountDebugValue,
useDeferredValue: mountDeferredValue,
useTransition: mountTransition,
useMutableSource: mountMutableSource,
useOpaqueIdentifier: mountOpaqueIdentifier,
unstable_isNewReconciler: enableNewReconciler,
};
HooksDispatcherOnUpdate
HooksDispatcherOnUpdate
: 第三种形态是函数组件的更新,既然与 fiber
之间的桥已经建好了,那么组件再更新,就需要 hooks
去获取或者更新维护状态。
/react/packages/react-reconciler/src/ReactFiberHooks.new.js
const HooksDispatcherOnUpdate: Dispatcher = {
readContext,
useCallback: updateCallback,
useContext: readContext,
useEffect: updateEffect,
useImperativeHandle: updateImperativeHandle,
useLayoutEffect: updateLayoutEffect,
useMemo: updateMemo,
useReducer: updateReducer,
useRef: updateRef,
useState: updateState,
useDebugValue: updateDebugValue,
useDeferredValue: updateDeferredValue,
useTransition: updateTransition,
useMutableSource: updateMutableSource,
useOpaqueIdentifier: updateOpaqueIdentifier,
unstable_isNewReconciler: enableNewReconciler,
};