我有一个减速器,当您单击菜单项时,它会连接基本价格,然后在用户单击该菜单项的修饰符后,它应该向状态添加一个修饰符对象,但它只是返回 mod_price对象而已。我希望它同时返回 base_price 和 mod_price,但它返回 mod_price 对象。下面是我的代码。任何帮助将不胜感激。
/*This shows the cart price for only the selected item next to where it says add to cart*/
export const cartPriceForSelectedItem = (state = [],action) => {
const {payload,type} = action;
switch (type) {
case SELECTED_PRICE :
const {base_price} = payload;
return state.concat({base_price: base_price});
case SET_MOD_PRICE_TOTAL :
return state.concat({mod_price: payload})
}
return state;
}
答案 0 :(得分:1)
如果 state 是一个对象,您正在寻找扩展运算符或 Object.assign
以返回具有合并属性的新状态。
return {
...state,
base_price: base_price
};
Object.assign
return Object.assign({}, state, {
base_price: base_price
});
需要注意的一点是,这些操作执行的是浅层合并,我认为在这种情况下这不是问题。
const initialState = [];
const SELECTED_PRICE = 'SELECTED_PRICE';
const SET_MOD_PRICE_TOTAL = 'SET_MOD_PRICE_TOTAL';
const cartPriceForSelectedItem = (state = [], action) => {
const {
payload,
type
} = action;
switch (type) {
case SELECTED_PRICE:
const {
base_price
} = payload;
return state.concat({
base_price: base_price
});
case SET_MOD_PRICE_TOTAL:
return state.concat({
mod_price: payload
})
}
return state;
}
const action1 = {
type: SELECTED_PRICE,
payload: {
"base_price": 20
}
};
const state1 = cartPriceForSelectedItem(initialState, action1);
console.log('state1', state1);
const action2 = {
type: SET_MOD_PRICE_TOTAL,
payload: 45
};
const state2 = cartPriceForSelectedItem(state1, action2);
console.log('state2', state2);