【发布时间】:2021-03-29 04:54:45
【问题描述】:
我正在重构我之前使用钩子“useStateWithCallback”的一个上下文的复杂状态管理。
我决定使用“useReducer”重构代码,使其更具可读性。
目前,我正在这样做:
export function ContentsProvider({ children }) {
const [contents, setContents] = useStateWithCallback(new Map([]));
const addContents = (newContents, callback = undefined) => {
setContents(
(prevContents) => new Map([...prevContents, ...newContents]),
callback
);
};
...
现在,在我的任何使用此上下文的应用程序组件上,我都可以这样做:
contents.addContents([ ... ], () => { ... });
只有当状态发生变化时才会执行回调。
有什么方法可以用 useReducer 实现这种行为吗?我的意思是,如果我将回调作为参数传递给我的提供者的方法,那么我将无法运行
useEffect(() => { callback?.() } , [contents]);
有什么想法吗?
我试过这个:
import { useReducer, useEffect } from 'react'
export const useReducerWithCallback = (
initialState,
reducer,
callback = undefined
) => {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
callback?.(state);
}, [state, callback]);
return [state, dispatch];
};
但它不起作用,因为在我的用例中,回调并不总是相同的,所以我不能用回调声明reducer。
【问题讨论】:
标签: javascript reactjs react-native react-hooks