【问题标题】:Why is not my immer reducer returning the new value even though the draft have changed?为什么即使草稿已经更改,我的 immer reducer 也没有返回新值?
【发布时间】: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,看看是否是问题所在。

标签: reactjs immer.js


【解决方案1】:

组件内部的produce 可能会在每次渲染时重新生成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
      
    

【讨论】:

  • 感谢您的意见!不幸的是它没有解决我的问题
猜你喜欢
  • 2020-11-21
  • 2021-07-17
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多