gpt4 book ai didi

reactjs - 为什么即使吃水已经改变,我的 immer reducer 也没有返回新值?

转载 作者:行者123 更新时间:2023-12-05 06:53:45 26 4
gpt4 key购买 nike

为什么我的 immer reducer 没有返回新值,即使 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;
...
}
}

,看起来好像变了,但是当状态应该更新时,返回的值是旧值。这与导致初始状态的新安装有什么关系吗?它似乎安装了两次。这与我拥有用于​​固定浸入式 reducer 的组件的功能组件有什么关系吗?

感谢所有帮助!

最佳答案

可能 produce 在 Component 内部在每次渲染时重新生成 reducer。尝试将这些更改为

// inside my component that produces the immer
function MyComponent() {
const immerReducer = produce(reducer); //<-- Remove it from here it is producing new reducer

// inside the immer reducer file
export const reducer = (draft, action) => { //<-- Put produce here
// export const reducer = produce(draft, action) => {} //<- Like this


关于reactjs - 为什么即使吃水已经改变,我的 immer reducer 也没有返回新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65698710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com