javascript - 更新数组挂钩中的对象反应js
问题描述
我试图通过按“向上”按钮来更新数量。
这是我的代码。
const increaseHandler = (x) => {
let newCart = [...props.cartItems];
let exist = newCart.find((item) => item.id === x.id);
if (exist) {
exist.quantity++;
} else {
exist = {
...props.cartItems,
quantity: 1,
};
}
newCart.push(exist);
props.setCartItems(newCart);
};
这是按钮:
<button className="up" onClick={() => increaseHandler(items)}>
up
</button>
每次我单击“向上”按钮时,它都会在 cartItems 上附加该项目的副本
我增加了数量,但它将对象附加到数组中。
解决方案
即使您对购物车项目数组进行了浅层复制,您仍然会使用后期增量来改变各个项目。
const increaseHandler = (x) => {
let newCart = [...props.cartItems];
let exist = newCart.find((item) => item.id === x.id);
if (exist) {
exist.quantity++; // <-- mutation!!
} else {
exist = {
...props.cartItems,
quantity: 1,
};
}
newCart.push(exist); // <-- adds duplicate items
props.setCartItems(newCart);
};
您仍然需要创建一个新的项目引用,浅复制属性并更新quantity
属性。您应该只将新元素推送到购物车数组中。
const increaseHandler = (x) => {
const newCart = [...props.cartItems];
let exist = newCart.find((item) => item.id === x.id);
if (exist) {
exist = {
...exist,
quantity: exist.quantity + 1;
};
} else {
exist = {
...props.cartItems,
quantity: 1,
};
newCart.push(exist);
}
props.setCartItems(newCart);
};
将前一个状态映射到下一个状态更为常见,我建议使用功能状态更新来确保从前一个状态正确更新,而不是在回调范围内关闭任何状态(可能是陈旧的)。
const increaseHandler = (x) => {
props.setCartItems(items => {
const inCart = items.some((item) => item.id === x.id);
if (inCart) {
return items.map((item) => item.id === x.id
? {
...item,
quantity: item.quantity + 1,
}
: item);
}
return items.concat({
...props.cartItems,
quantity: 1,
});
});
};
推荐阅读
- angular - Observable.forkJoin 在 forkJoin 下显示一个波浪线
- android - longclickitem recyclerView时在android中显示弹出菜单
- javascript - D3 实现:D3 地图背后的自定义拓扑图
- java - HazelcastInstance 未使用 Spring Bean 调用
- python - Python将CSV文件导入sqlite3删除复制
- r-markdown - 在 R Bookdown 中每个 GitBook 风格的网页章节之后重新开始尾注编号
- ios - 如何从返回[String:AnyObject] Swift4的快速响应中获取价值
- c# - AWS S3 的 C# UI 未更新
- node.js - 如何在 DynamoDB AWS 中为 order by 创建索引表
- javascript - 在数组中创建对象的副本