使用Reducer从阵列中删除所有项目-React

时间:2019-07-02 16:50:49

标签: javascript reactjs react-redux

下面是我用来从数组(购物车)中删除项目的reducer的结构。在下面的代码中,我一次只能删除一个single item。单击触发减速器的删除按钮或图标时,如何删除购物车上的所有物品?

PS:React入门

Reducer.JS

export default (state = INIT_STATE, action) => {
    switch (action.type) {

        case ON_DELETE_ITEM_FROM_CART:
            let index = state.cart.indexOf(action.payload)
            return update(state, {
                cart: {
                    $splice: [[index, 1]]
                }
            });
   }

2 个答案:

答案 0 :(得分:0)

export default (state = INIT_STATE, action) => {
    switch (action.type) {
        case ON_DELETE_ALL_ITEMS_FROM_CART:
            return update(state, { cart: [] });
   }

答案 1 :(得分:0)

在这里你可以从我的 reducer 中清空你的完整购物车代码

   const initialState = {
  items: {},
  totalAmount: 0,
};
const cartItems = (state = initialState, action) => {
  switch (action.type) {


case CLEAR_CART:
        
          return  state={ items: {}, totalAmount: 0, }