【发布时间】:2021-04-21 06:28:57
【问题描述】:
所以我试图在我的 React-redux 网站上添加一个购物车功能,但我遇到了一个非常奇怪的情况。所以这就是我从动作的有效负载中得到的,例如:
{
info: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
id: 1,
price: 109.95,
image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg',
count: 5,
totalPrice: 549.75
}
所以我要做的是,当尝试添加与此 id 相同的商品时,不要添加它,而是增加购物车中已存在的具有相同 id 的商品的数量:
const index = state.currentCart.findIndex((x) => x.id === id);
return {
...state,
currentCart: [
...state.currentCart,
state.currentCart[index].count += 1,
(state.currentCart[index].totalPrice =
state.currentCart[index].price * state.currentCart[index].count),
],
};
计数本身增加了,但同时发生了一些非常奇怪的事情。 产品的总价格及其计数也作为 currentCart 数组的元素添加,当唯一应该发生的事情是使用有效负载中的 id 更新购物车项目的计数时, 这是触发此操作时 currentCart 数组发生的情况:
currentCart: [
{
info: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
id: 1,
price: 109.95,
image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg',
count: 6,
totalPrice: 659.7
},
2,
219.9,
3,
329.85,
4,
439.8,
5,
549.75,
6,
659.7
]
}
我确定我没有改变状态,提前谢谢你!
【问题讨论】:
-
你在说
currentCart数组中的奇怪值?喜欢2, 219.9, -
是的,没错,它只是突然出现,或者我做错了什么。
-
尝试删除
return语句中的这一行,然后重试(state.currentCart[index].totalPrice =state.currentCart[index].pricestate.currentCart[index].count), -
嘿,对不起,我把退货复制错了,我修好了,你能再看看吗
-
hmmm... 尝试将您的设置调用封装在
{}中。currentCart:[...state.currentCart,{state.currentCart[index].count += 1, and remaining setter}].
标签: javascript reactjs redux react-redux reducers