如何从 redux 减少状态中使用的数组对象中删除元素?

时间:2021-02-08 03:45:17

标签: reactjs redux reducers

在我的 react 应用中,我使用 redux 创建了一个 store 和 reducer。

我有一个状态名称“cart”,它是一个对象数组。

我想删除一个元素,我只在 reducer 情况下将其作为有效负载传递给 id。

如何从此状态中删除 id 等于有效负载 ID 的元素?

这是购物车状态结构

enter image description here

const reducer = (state = initialState, action) => {
       case actionTypes.QUANTITY_COUNT:
            const newCart = {...state.cart};
            if (newCart[action.id].quantity === 1){
                 //here i want to remove element from cart/newCart of Id as action.id
              }
}

2 个答案:

答案 0 :(得分:1)

实际上 delete 关键字不是为执行此任务而设计的。此外,reducer 背后的想法是创建一个新状态,因此复制状态然后删除元素是您必须尝试在代理包(例如 immer 而不是 js 本身)中执行的操作。

这里有一些处理对象的技巧,因为有很多关于对象状态变化的问题。

const state = { isActive: true, props: { userId: {} } }
Object.keys(state) // ['isActive', 'props']
Object.entries(state) // [['isActive', true], ['props', { userId: {} }]]
Object.keys(state).map((key, index) => state[key]) // // [true, { userId: {} }]

正如我提到的,删除在这里并没有起到很好的作用,相反,更改子部件对象的更好方法是使用 immer 或 filter


const newCart = Object.keys(state.cart).filter(() => state.cart[action.id].quantity !== 1)

答案 1 :(得分:0)

你可以试试这个逻辑,这适用于我的情况:

      const reducer = (state = initialState, action) => {
       case actionTypes.QUANTITY_COUNT:
            const newCart = {...state.cart};
            if (newCart[action.id].quantity === 1){
                  delete newCart[action.id]
                 
              }
}