我正在管理一个由状态组成的购物车数组:
const [cart, setCart] = useState([{
key: 1
name: 'Product Name'
value: 399
productID: 1456我通过一个函数向它添加项,并按键进行排序:
function addToFav() {
setFavs((arr) => {
const newFavs = [...arr];
const existingItem = newFavs.find((i) => i.id === infos[id-2].id);
if (existingItem) {
console.log('Este item já está nos favoritos');
} else {
newFavs.push({
nome: infos[id-2].nomeCompleto,
value: infos[id-2].valor,
id: infos[id-2].id,
quantity: 1,
key: infos[id-2].key
}).sort((a, b) => {
return a.key - b.key
});
}
return newFavs;
});
} 我的加减函数工作得很好。但我需要一个函数将对象从数组中移除。现在,我用的是:
export const CartElement = (props) => {
...
const cartRemove = (index) => {
setCart([
...cart.splice(index, 1)
])
}
...
<... onClick={() => { cartRemove(props.key - 1)}}>问题是:在数组中找不到带有函数的对象索引。由于数组中并不总是有所有的键,所以键不能工作。如何在状态数组上找到“props”对象的索引?或者有其他方法可以从购物车篮中分割特定的数组,比如Array.filter之类的。
发布于 2022-06-07 19:32:34
如何显示物品?如果使用map方法,则它的回调可以接收索引参数。您应该将它传递给您的函数addToFav或cartRemove。
结帐文档
https://stackoverflow.com/questions/72536628
复制相似问题