reactjs 错误:immer生成器返回了新值 * 并 * 修改了其草稿,返回新值 * 或 * 修改草稿

nszi6y05  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(444)

我的代码:

removeIndexCart: (state, action) => {
      const IteamIndex_dec = state.cart.findIndex(
        (iteam) => iteam.id === action.payload.id
      );

      if (state.cart[IteamIndex_dec].qnty >= 1) {
        const dltiteams = (state.cart[IteamIndex_dec].qnty -= 1);
        console.log([...state.cart, dltiteams]);

        return {
          ...state,
          cart: [...state.cart],
        };
      } else if (state.cart[IteamIndex_dec].qnty === 1) {
        const data = state.cart.filter((el) => el.id !== action.payload);

        return {
          ...state,
          cart: data,
        };
      }
    },

我想用索引减少所选产品,但我遇到了这个错误。

2uluyalo

2uluyalo1#

似乎reducer函数既尝试使用Immer(由redux-toolkit自动应用)修改代理state,又返回一个新值,这导致了错误。
有关使用redux-toolkit reducer with immer的详细信息
也许可以考虑始终修改缩减器中的代理state

// Only works in redux-toolkit with immer

removeIndexCart: (state, action) => {
  const IteamIndex_dec = state.cart.findIndex(
    (iteam) => iteam.id === action.payload.id
  );
  if (state.cart[IteamIndex_dec].qnty > 1) {
    state.cart[IteamIndex_dec].qnty -= 1;
  } else if (state.cart[IteamIndex_dec].qnty === 1) {
    state.cart = state.cart.filter((el) => el.id !== action.payload);
  }
};

或者,尝试始终返回新值而不修改代理state

removeIndexCart: (state, action) => {
  const IteamIndex_dec = state.cart.findIndex(
    (iteam) => iteam.id === action.payload.id
  );
  if (state.cart[IteamIndex_dec].qnty > 1) {
    const updatedItem = {
      ...state.cart[IteamIndex_dec],
      qnty: state.cart[IteamIndex_dec].qnty - 1,
    };

    const updatedCart = [...state.cart];
    updatedCart[IteamIndex_dec] = updatedItem;

    return {
      ...state,
      cart: updatedCart,
    };
  } else if (state.cart[IteamIndex_dec].qnty === 1) {
    const data = state.cart.filter((el) => el.id !== action.payload);

    return {
      ...state,
      cart: data,
    };
  }
};

相关问题