【问题标题】:React - Redux-Toolkit items in cartReact - 购物车中的 Redux-Toolkit 项目
【发布时间】:2022-08-15 02:22:59
【问题描述】:

我正在学习使用 redux-toolkit 做出反应。我在那里坚持一些行动。

我想在购物车中添加数量,所以如果我多次添加相同的商品,它应该像 X1/x2/x3...等。 而且我想删除项目/项目,但只能使用相同的 ID(当我单击删除时,只删除那个前。APPLE)

    import { createSlice } from \"@reduxjs/toolkit\";
const initialState = {
  hidden: true,
  cartItems: 0,
  itemsInCart: [],
  quantity: 0,
  totalCount: 0,
};

export const cartSlice = createSlice({
  name: \"cart\",
  initialState,
  reducers: {
    removeItem: (state, action) => {},
    removeAll: (state) => {
      state.cartItems = 0;
      state.itemsInCart = [];
      state.totalCount = 0;
    },
    addToCart(state, action) {
      state.itemsInCar = state.itemsInCart.push(action.payload);
      state.cartItems += 1;
      state.totalCount += action.payload.price;
    },
    showCart: (state) => {
      state.hidden = !state.hidden;
    },
  },
});
export const { showCart, addToCart, removeAll, removeItem } = cartSlice.actions;

export default cartSlice.reducer;
  • 你在 addToCard 上传递什么并给出 state.itemsInCar 的示例输出
  • 在 addToCart 我传递 {item} (例如 {id:0,name:\'\',image:\'\'.....})

标签: reactjs redux redux-toolkit


【解决方案1】:
addToCart: (state, action) => {
      const itemInCart = state.cart.find((item) => item.id === action.payload.id);
      if (itemInCart) {
        itemInCart.quantity++;
      } else {
        state.cart.push({ ...action.payload, quantity: 1 });
      }
    },

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2021-01-29
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多