Jquery 如何将对象添加到reducer数组中?
我需要将Actions中的对象添加到Reducers数组中。该值首次添加到减速器中。当我再次分派操作时,它将用对象覆盖数组中的现有值 检查以下代码: 行动:Jquery 如何将对象添加到reducer数组中?,jquery,html,reactjs,redux,react-hooks,Jquery,Html,Reactjs,Redux,React Hooks,我需要将Actions中的对象添加到Reducers数组中。该值首次添加到减速器中。当我再次分派操作时,它将用对象覆盖数组中的现有值 检查以下代码: 行动: let itemImgObj = { itemid: "", itemimgurl: "" }; export const setItemsImages = (itemid, itemimgurl) => { itemImgObj.itemid = itemid; itemImgObj.itemimgurl = ite
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;
}
};
如何使用每次分派时的操作中的对象更新数组值?原因是您总是将空数组的
state
的值设置为cartItemsImages
。因此,每当调用reducer时,state的值总是一个空数组,这就是它重写现有值而不是追加新值的原因
您可以执行以下代码:
// 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;
}
};
原因是您总是将空数组的
state
的值设置为cartItemsImages
。因此,每当调用reducer时,state的值总是一个空数组,这就是它重写现有值而不是追加新值的原因
您可以执行以下代码:
// 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;
}
};