【发布时间】:2021-08-15 20:24:32
【问题描述】:
我目前正在研究如何管理全局状态。一种似乎很流行的模式是多上下文模式:
export default function makeStore<State, Actions = string>(
reducer: Reducer<State, Actions>,
initalState: State
): [
({ children }: { children: ReactElement }) => JSX.Element,
() => Dispatch<Actions>,
() => State
] {
const dispatchContext = createContext<Dispatch<Actions>>(() => null);
const storeContext = createContext<State>(initalState);
const StoreProvider = ({ children }: { children: ReactElement }) => {
const [store, dispatch] = useReducer<Reducer<State, Actions>>(
reducer,
initalState
);
return (
<dispatchContext.Provider value={dispatch}>
<storeContext.Provider value={store}>
{children}
</storeContext.Provider>
</dispatchContext.Provider>
);
};
function useDispatch() {
return useContext(dispatchContext);
}
function useStore() {
return useContext(storeContext);
}
return [StoreProvider, useDispatch, useStore];
}
这里的想法是,将dispatch 和state 分离到它们自己的上下文中可以以某种方式避免不必要的重新渲染。通过使用useDispatch 或useState,组件可以“订阅”仅状态或调度。在处理了一两分钟后,我发现自己想知道这种模式对重新渲染有何影响。
据我所知,每当状态发生变化时,React 都会重新渲染提供者下方的所有内容。将dispatch 分离到它们自己的上下文中会对 e 产生影响。 G。挂钩的依赖数组(使渲染性能更高)也应该可以忽略不计,因为调度是跨渲染的稳定值。
与仅使用一个上下文相比,使用这种模式有什么优势吗?
【问题讨论】:
标签: reactjs react-hooks react-context