gpt4 book ai didi

javascript - 用于添加到购物车的 redux concat 数组

转载 作者:行者123 更新时间:2023-12-01 01:46:03 25 4
gpt4 key购买 nike

按下“添加到购物车”按钮后,我需要从我的化简器连接一个数组。

我尝试过推送,但似乎不起作用。

import { combineReducers } from 'redux';

import { DATA_AVAILABLE,
ADD_TO_CART,
GET_CART_DATA
} from "../actions/" //Import the actions types constant we defined in our actions

let dataState = { data: [], loading:true };
let cartState = { data: [] };


const dataReducer = (state = dataState, action) => {
switch (action.type) {
case DATA_AVAILABLE:
state = Object.assign({}, state, { data: action.data, loading:false });
return state;
default:
return state;
}
};

const cartReducer = (state = cartState, action) => {
switch (action.type) {
case ADD_TO_CART:
state = Object.assign({}, state, { data: [action.data]});
//console.log("state data => "+state.data);
return state;
default:
return state;
}
};

// Combine all the reducers
const rootReducer = combineReducers({
dataReducer,
cartReducer,
// ,[ANOTHER REDUCER], [ANOTHER REDUCER] ....
})

export default rootReducer;

ADD_TO_CART 事件期间,每次单击“添加到购物车”按钮时,reducer 都会替换所有数据。相反,我需要连接这些商品,以便将它们显示到我的购物车列表中。

最佳答案

看起来你可能想要:

case ADD_TO_CART:
return Object.assign({}, state, {
data : state.data.concat(action.data)
});

如果您的应用程序设置中有可用的对象扩展语法(如果您使用 Create-React-App,则默认情况下启用该语法),您可以将其稍微简化为:

case ADD_TO_CART:
return {...state, data : state.data.concat(action.data) }

关于javascript - 用于添加到购物车的 redux concat 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51954546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com