如何将对象添加到reducer数组中?

时间:2019-05-29 10:54:32

标签: jquery html reactjs redux react-hooks

我需要将操作中的对象添加到Reducers数组中。第一次将值添加到减速器中。当我再次分派动作时,它会用对象覆盖数组中的现有值。

检查以下代码:

操作:

let itemImgObj = {
  itemid: "",
  itemimgurl: ""
};
export const setItemsImages = (itemid, itemimgurl) => {
  itemImgObj.itemid = itemid;
  itemImgObj.itemimgurl = itemimgurl;
  console.log("as", itemImgObj);
  return {
    type: 'SET_ITEMS_IMAGES',
    itemImgObj
  };
};

减速器:

const Reducer = (state = { cartItemsImages= [] }, action) => {
  console.log(action);
  switch (action.type) {
    case 'SET_ITEMS_IMAGES':
      return {
        ...state,
        cartItemsImages: [...state.cartItemsImages, action.itemImgObj]
      };
    default:
      return state;
  }
};

如何通过每次调度中的操作使用对象更新数组值?

1 个答案:

答案 0 :(得分:0)

原因是您总是将state的值设置为空数组的cartItemsImages。因此,每当调用reducer时,状态值始终是一个空数组,这就是为什么它覆盖现有值而不是附加新值的原因。

您可以执行以下代码:

// declare a new const which contains your cartItemsImages
const initialSate = {
   cartItemsImages: []
};

const Reducer = (state = initialSate, action) => {
  console.log(action);
  switch (action.type) {
    case 'SET_ITEMS_IMAGES':
      return {
        ...state,
        cartItemsImages: [...state.cartItemsImages, action.itemImgObj]
      };
    default:
      return state;
  }
};
相关问题