如何防止Redux商店中的重复物品?

发布于 2025-02-08 08:40:38 字数 1131 浏览 1 评论 0原文

我正在使用redux-toolkit。我正在尝试防止商店中的重复项目,并且还希望是否有任何用户试图再次添加同一项目。这次我想简单地更新她的数量。

这是我的代码:

import { createSlice, current } from "@reduxjs/toolkit";

const initialState = {
  product: [],
};

export const cartSlice = createSlice({
  name: "cart",
  initialState: initialState,
  reducers: {
    addproduct: (state, action) => {
      console.log(action.payload._id) // here _id is ok
      const exist = state.product.find((pro) => pro._id === action.payload._id)
      console.log(exist) //output undefined
      state.product = [...state.product, action.payload];
    },
  },
})

export const { addproduct } = cartSlice.actions;
export default cartSlice.reducer;

我的JSON文件:

[
  {
    "_id": "62ad4c398bc6d37767e44423",
    "name": "singu pizza",
    "size": "small",
    "category": "neapolitan",
    "price": 250,
    "image": "https://i.ibb.co/zVbq909/pizza.png"
  },
  {
    "_id": "62ad4c398bc6d37767e44424",
    "name": "singu pizza",
    "size": "large",
    "category": "neapolitan",
    "price": 250,
    "image": "https://i.ibb.co/zVbq909/pizza.png"
  }
]

I am using Redux-toolkit. I am trying to prevent duplicate items in my store and also want to if any user tries to add the same item again. This time I want to simple update her quantity.

Here is my code:

import { createSlice, current } from "@reduxjs/toolkit";

const initialState = {
  product: [],
};

export const cartSlice = createSlice({
  name: "cart",
  initialState: initialState,
  reducers: {
    addproduct: (state, action) => {
      console.log(action.payload._id) // here _id is ok
      const exist = state.product.find((pro) => pro._id === action.payload._id)
      console.log(exist) //output undefined
      state.product = [...state.product, action.payload];
    },
  },
})

export const { addproduct } = cartSlice.actions;
export default cartSlice.reducer;

My JSON file:

[
  {
    "_id": "62ad4c398bc6d37767e44423",
    "name": "singu pizza",
    "size": "small",
    "category": "neapolitan",
    "price": 250,
    "image": "https://i.ibb.co/zVbq909/pizza.png"
  },
  {
    "_id": "62ad4c398bc6d37767e44424",
    "name": "singu pizza",
    "size": "large",
    "category": "neapolitan",
    "price": 250,
    "image": "https://i.ibb.co/zVbq909/pizza.png"
  }
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟火散人牵绊 2025-02-15 08:40:38

假设您的产品上有一个数量属性:

    addproduct: (state, action) => {
      const item = state.product.find((pro) => pro._id === action.payload._id)
      if (item) {
        item.quantity++
      } else {
        state.product.push(action.payload)
      }
    },

Assuming that there is a quantity property on your product:

    addproduct: (state, action) => {
      const item = state.product.find((pro) => pro._id === action.payload._id)
      if (item) {
        item.quantity++
      } else {
        state.product.push(action.payload)
      }
    },
木格 2025-02-15 08:40:38

如果您在项目中使用理智,请按照以下代码进行更新的数量,而不是在购物车中再次添加相同的产品,如果您不使用理智,请查看下面的代码,我相信它会给您一些解决您的问题的想法。

更新您的CARTSLICE中的代码:

const initialState = {
  product: [],
};

export const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    addproduct: (state, { payload }) => {
      let newItem = payload;
      const existItem = state.products.find((item) => item._id === payload._id);

      state.products = existItem ? state.products.map((item) => item._id === existItem._id ? newItem : item) : [...state.products, newItem]
    }
  },
})

在您要使用reducer的页面中添加以下内容:

const { products } = useSelector(store => store.cart)

const addToCart = () => {
    let cartItem = products.find(item => item._id === product._id)
    let quantity = cartItem ? cartItem.quantity + 1 : 1;
    dispatch(() => addproduct({
        _id: product._id,
        name: product.name,
        size: product.size,
        category: product.slug.current,
        price: product.price,
        image: urlFor(product.image),
        quantity
      }))
  }

addtocartonclick函数,不需要将数量属性添加到您的JSON文件中,也不需要在选择“在购物车中”时添加API。上面的数量将检查该项目是否存在于购物车中的数量为1,并且将添加到产品项目的对象中,如果该项目确实存在于购物车中,则该项目将通过一个更新数量。

现在一切都应该很好。如果您有错误,请随时给我发消息,我很乐意为您提供帮助

If you are using sanity in your project follow the code below, it will update your quantity instead of adding the same product again in the cart, if you are not using sanity have a look at the code below I am sure it will give you some ideas to solve your problem.

Update your cartSlice with the code below :

const initialState = {
  product: [],
};

export const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    addproduct: (state, { payload }) => {
      let newItem = payload;
      const existItem = state.products.find((item) => item._id === payload._id);

      state.products = existItem ? state.products.map((item) => item._id === existItem._id ? newItem : item) : [...state.products, newItem]
    }
  },
})

In the the page you want to use the reducer in add this:

const { products } = useSelector(store => store.cart)

const addToCart = () => {
    let cartItem = products.find(item => item._id === product._id)
    let quantity = cartItem ? cartItem.quantity + 1 : 1;
    dispatch(() => addproduct({
        _id: product._id,
        name: product.name,
        size: product.size,
        category: product.slug.current,
        price: product.price,
        image: urlFor(product.image),
        quantity
      }))
  }

addToCart is an onClick function, you do not need to add quantity property to your json file or the api it will be added when the product is selected to be in cart. The quantity above it will check if the item does not exist in the cart the quantity will be 1 and it will be added to the object of the product item, If the item does exist in the cart it will update the quantity by one.

Now everything should work just fine. If you had an error please feel free to message me, I would be more than happy to help you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文