Redux Toolkit从数组中删除一个项目(所有内容都将被删除)

1qczuiv0  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(194)

我正在尝试用redux和react创建一个类似购物车的系统。产品作为一个完整的对象存储在redux切片数组中。产品对象如下所示:

这是我的复选框输入代码

const products = useSelector((state) => state.prodSlice.value)

  const handleChange = (event) => {
    const button = event.target
    const isActive = button.checked
    const itemName = event.currentTarget.id
    const items = products.items

    const itemsArr = {}

    items.forEach((items) => {
      if (items.productName === itemName) {
        itemsArr['productName'] = items.productName
        itemsArr['total'] = items.total
        itemsArr['quantity'] = items.quantity

        if (isActive) {
          dispatch(checkout({products: itemsArr}))
        } else {
          dispatch(removeItem({products: itemsArr}))
        }

      }
    })
  }

当向阵列添加产品时,没有问题,

然而,当我取消选中一个项目,并获得数组的值时,它只返回一个空数组,而不是只删除一个项目。

我只想从数组中删除那一项,这是我的redux切片代码

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

const initialState = {
    value: {
        products: [],
    }
}

export const checkOut = createSlice({
    name: "checkout",
    initialState,
    reducers: {
        checkout: (state, action) => {
            state.value.products.push(action.payload)
        },
        removeItem: (state, action) => {
            state.value.products = state.value.products.filter((products) => products.produdctName !== action.payload.productName)

        }
    }
})

export const { checkout, removeItem } = checkOut.actions
export default checkOut.reducer

我希望有人能帮助我

wydwbb8l

wydwbb8l1#

removeItem约简器应该只返回过滤后的数组

removeItem: (state, action) => {
            return state.value.products.filter((products) => products.productName !== action.payload.productName)
        }

相关问题