javascript - Reducer 突然在商店中添加商品
问题描述
所以我试图在我的 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
]
}
我确定我没有改变状态,提前谢谢你!
解决方案
不,它们不是凭空而来的,您正在积极地将值添加到数组中。您似乎对如何正确处理状态有点困惑。您要么选择一种不可变的方法(如果您使用 react,我真的建议您这样做),或者您选择改变您的引用。
在 javascript 中,当您进行分配时,该分配也会返回正在分配的值,例如这里:
let x = 1
let b = x+=1
// b is now 2 and x is 2
let c = b += 2
// b is now 4 and c is also 4
这正是您的数组分配中发生的事情。您首先将旧版本的数组传播到新版本(制作副本)上,然后同时改变对当前汽车的引用(这是关键部分),您正在保存那些的返回值数组本身的赋值。看看数组上的值,它们是你操作的结果:
count (1) += 1 // 2
price (109.95) * count (2) = 219.9,
count (2) += 1 // 3
price (109.95) * count (3) = 329.85
... etc
因此,您在阵列上拥有的是计数和总价格值的历史记录。
这是您的代码中发生的事情的细分:
// Will allways be at index 0, because you add it as first element
// and then you keep copying the array below
const index = state.currentCart.findIndex((x) => x.id === id);
return {
...state,
currentCart: [
// Here you are copying the old array into the new one,
// keeping the current car at the first position
...state.currentCart,
// Here you are updating the values of the object at index 0
// and at the same time you are adding those values at
// the end of the array
state.currentCart[index].count += 1,
(state.currentCart[index].totalPrice =
state.currentCart[index].price * state.currentCart[index].count),
],
};
您要做的是每次都构建一个新的 currentCart 。您还想为 currentCart 使用对象,而不是数组。如果您想在购物车中保留商品列表,我建议您在购物车上创建一个名为 items 的嵌套属性,并将其设为数组。您的代码示例没有向我们展示您从哪里获取操作,但我会为您提供一个示例,假设您刚刚拥有它并且要添加到购物车的新项目来自有效负载。
const currentCart = state.currentCart;
const newItem = action.payload
return {
...state,
currentCart: {
...currentCart,
count: currentCart.count + 1
totalPrice: (newItem.price * newItem.count) + currentCart.totalPrice,
items: [...currentCart.items, newItem]
},
};
推荐阅读
- google-apps-script - Google Apps 脚本 - webapp 中使用的类方法的回调
- angular - 如何在 Angular 中的 http 服务中实现页面加载器系统
- image - 如何从 Windows 剪贴板中获取图像数据
- git - 仅为 git log 设置漂亮的格式
- linux - 阻止用户查看公用文件夹
- python - 将渐变样式应用于多个子集中的 pandas DataFrame
- c# - 在 IServiceCollection.AddLogging (C#/.net Core) 中获取服务
- c# - Unity GameObject OnclickEvent
- mongodb - 在节点/快递中包含插入的数据(如 ObjectId)以响应
- docker - kubernetes 无法转发端口