Redux的组成
Store
一个对象,用来存储application level的state,也携带了一些Redux相关的方法,虽然理论上可以支持创建多个,但应该遵序one application one store的原则。
Actions
Actions是plain objects,只用来形容发生了什么(type field),不会形容State如何更新。
Reducers
Reducers是pure function,接收旧state和action,重新计算application state。
React Hooks 与 Redux
createStore
接收三个参数reducer, initial state 和 enhancer middleware,返回一个包含dispatch,subscribe,getState,replaceReducer的对象,局部变量用来存放currentState, currentReducer, currentListeners, isDispatching
Provider
Provider就是一个HOC,本身没有任何试图内入,只展示children,它接收store, context, children, serverState, 返回 <Context.Provider value={contextValue}>{children}</Context.Provider>
其中contextValue来自:
const contextValue = useMemo(() => {
const subscription = createSubscription(store)
return {
store,
subscription,
getServerState: serverState ? () => serverState : undefined,
}
}, [store, serverState])
store是createStore
出来的, 由开发者传入
subscription由createSubscription工厂函数创建
getServerState是SSR相关,不做讲解
Provider还做了一件事:
const previousState = useMemo(() => store.getState(), [store]);
获取了一次最新 state 并命名为 previousState,只要 store 单例不发生变化,它是不会更新的。一般项目中也不太会改变 redux 单例。
useIsomorphicLayoutEffect(() => {
const { subscription } = contextValue;
subscription.onStateChange = subscription.notifyNestedSubs;
subscription.trySubscribe();
if (previousState !== store.getState()) {
subscription.notifyNestedSubs();
}
return () => {
subscription.tryUnsubscribe();
subscription.onStateChange = undefined;
};
}, [contextValue, previousState]);
useIsomorphicLayoutEffect
export const canUseDOM = !!(
typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof window.document.createElement !== "undefined"
);
export const useIsomorphicLayoutEffect = canUseDOM
? useLayoutEffect
: useEffect;
这个hook内容很简单,服务器端使用useEffect
,客户端使用useLayoutEffect
, useEffect
与useLayoutEffect
的区别在于前者不会阻塞渲染,异步执行,后者阻塞渲染,同步执行,因此useLayoutEffect
与componentDidMount
是等价的。
为什么要放在useLayoutEffect
/useEffect
中来做,因为useEffect
的调用时自下而上的,这是能确保子组件的渲染更新都已经发生了
useSelector
这里要提到一个概念叫组件外部状态(区别于组件内部状态以及局部内部状态),组件外部状态对象一般要实现的通用接口
interface ExternalStore<T> {
getState(): T;
subscribe(listener: () => void): () => void;
dispatch(updater: T | ((prevState: T) => T)): void;
}
你会发现跟store很像,那么我们可以写一个hook用来监听它的变化
export const useCustomStore = <T>(store: ExternalStore<T>) => {
const [state, setState] = useState(store.getState());
useEffect(() => {
const unsubscribe = store.subscribe(() => {
setState(store.getState());
});
return () => { unsubscribe(); };
}, []);
return state;
};
通过useState创建状态机,并且通过getState方法赋予其初始值,最后通过subscribe函数监听state的变化,调用setState方法更新state值。至此,我们就实现了一个有缺陷的useSelector方法(无法返回state中的某个属性)。
当然,我们也可以将这件事交给React负责,使用useSyncExternalStore API:
export const useExternalStore = <T>(store: ExternalStore<T>) => {
return useSyncExternalStore(
store.subscribe,
store.getState
);
};
那么,真实的useSelector使用的是什么呢?它使用了React 额外提供了带 Selector 优化的useSyncExternalStoreWithSelector。假如不带selector,那么我们每次监听的state变化范围是整体,但如果带了selector,我们可以只关心局部的变化,这个API需要额外提供selector函数,也可以选择性提供isEqual函数。于是就产生了如下的代码:
let useSyncExternalStoreWithSelector = notInitialized as uSESWS
const refEquality: EqualityFn<any> = (a, b) => a === b
export function createSelectorHook(
context = ReactReduxContext
): <TState = unknown, Selected = unknown>(
selector: (state: TState) => Selected,
equalityFn?: EqualityFn<Selected>
) => Selected {
const useReduxContext =
context === ReactReduxContext ? useDefaultReduxContext : () => useContext(context)
return function useSelector<TState, Selected extends unknown>(
selector: (state: TState) => Selected,
equalityFn: EqualityFn<NoInfer<Selected>> = refEquality
): Selected {
const { store, subscription, getServerState } = useReduxContext()!
const selectedState = useSyncExternalStoreWithSelector(
subscription.addNestedSub,
store.getState,
getServerState || store.getState,
selector,
equalityFn
)
useDebugValue(selectedState)
return selectedState
}
}
export const useSelector = createSelectorHook()
可以看出useSelector其实就是createSelectorHook的闭包,闭包的参数均由useDefaultReduxContext提供
useReduxContext
export function useReduxContext(): ReactReduxContextValue | null {
const contextValue = useContext(ReactReduxContext)
return contextValue
}
createContext<ReactReduxContextValue>(null as any)
useContext
Context的作用就是对它所包含的组件树提供全局数据共享。可以使用useContext跨域组件(爷孙,兄弟)之间传递变量,实现数据共享。
useDispatch
function createDispatchHook<S = RootStateOrAny, A extends Action = AnyAction>(
context?: Context<ReactReduxContextValue<S, A>> = ReactReduxContext
) {
const useStore =
context === ReactReduxContext ? useDefaultStore : createStoreHook(context);
return function useDispatch<
AppDispatch extends Dispatch<A> = Dispatch<A>
>(): AppDispatch {
const store = useStore();
return store.dispatch;
};
}
export const useDispatch = createDispatchHook();
useDispatch
非常简单,就是通过useStore()
拿到 redux store,然后返回store.dispatch
,用户就能使用这个dispatch派发action了。