【发布时间】:2021-01-13 09:08:54
【问题描述】:
为什么我的 immer reducer 没有返回新值,即使在减速器内部的草稿已经改变?我正在使用 console.log 检查我的草稿是否在 immerReducer 中发生了更改:
// inside my component that produces the immer
function MyComponent() {
const immerReducer = produce(reducer);
const [state, dispatch] = useReducer(immerReducer, initialState);
const contextValue = useMemo(() => [state, dispatch], [state, dispatch]);
const location = useLocation();
useEffect(() => console.log("mounted"), []); // mounted twice
useEffect(() => {
dispatch({ type: ACTIONS.SET_MODE, pathname: location.pathname })
}, [location.pathname]);
console.log(state.mode); // I can se that this returns the "old" value, the initial value
return (
<MyContext.Provider value={contextValue}>
{state.mode === MODES.DELETE ? <Deleted /> : <New />
</MyContext.Provider>
);
}
// inside the immer reducer file
export const reducer = (draft, action) => {
switch (action.type) {
case ACTIONS.SET_MODE:
if (action.pathname.endsWith(MODES.DELETE)) {
draft.mode = MODES.DELETE;
} else if (action.pathname.endsWith(MODES.EDIT)) {
draft.mode = MODES.EDIT;
} else {
draft.mode = MODES.NEW;
}
console.log("draft", draft.mode); // I can see that this logs out the wanted value
return draft;
...
}
}
,看起来好像变了,但是当状态应该已经更新时,返回的值是旧值。这与导致初始状态的新安装有什么关系吗?它似乎安装了两次。这与我拥有一个用于保持浸入式减速器的组件的功能组件有什么关系吗?
感谢所有帮助!
【问题讨论】:
-
您应该在问题中添加更多代码。目前,根本无法理解。
-
@tsfahmad 我尝试添加更多代码。现在是不是更容易理解了?
-
您可以尝试
useImmerReducer挂钩,看看是否有帮助。也可以尝试至少暂时删除useMemo,看看是否是问题所在。