javascript - ReactJS - 如何从功能组件中的数组中删除项目?
问题描述
我正在尝试使用 ReactJS 创建一个简单的购物车,并且我想出了一个潜在的出路,但是每当我单击删除按钮时,我已经设置它并没有真正从购物车中删除物品。所以这些是我的状态经理对这里:
let[product, setProduct] = useState([])
//The function bellow is what I use to render the products to the user
const[item] = useState([{
name: 'Burger',
image: '/static/media/Burger.bcd6f0a3.png',
id: 0,
price: 16.00
},
{
name: 'Pizza',
image: '/static/media/Pizza.07b5b3c1.png',
id: 1,
price: 20.00
}])
我有一个将 item 中的对象添加到产品数组的函数,然后我有一个应该删除它们的函数,如下所示:
const removeItem=(idx)=>
{
// let newProduct = product.splice(idx,1)
// setProduct([product,newProduct])
// $('.showItems').text(product.length)
// product[idx]=[]
product.splice(idx,1)
if(product.length<=0)
{
$('.yourCart').hide()
}
}
从这里调用这个函数:
{product.map((item, idx)=>
<div className='yourCart' key={idx}>
<hr></hr>
<div>
<img src ={item.image}></img>
<h3 className='burgerTitle'>{item.name}</h3>
<h4><strong>$ {item.price}.00</strong></h4>
<Button variant='danger' onClick={()=>removeItem(idx)}>Remove</Button>
</div>
<br></br>
</div>)}
问题是我尝试使用 splice、setState,我什至尝试清除整个数组并添加在对其应用过滤器函数后留下的元素,但这一切都无济于事。我怎样才能做到这一点,当我单击删除按钮时,它会从数组中删除特定项目?
解决方案
您需要使用setProduct
useState 挂钩提供的突变方法来改变product
状态。
const removeItem = (id) => {
const index = product.findIndex(prod => prod.id === id); //use id instead of index
if (index > -1) { //make sure you found it
setProduct(prevState => prevState.splice(index, 1));
}
}
用法
<Button variant='danger' onClick={()=>removeItem(item.id)}>Remove</Button>
作为旁注:
在处理数组中的项目时考虑使用明确的 id 值,而不是数组中的索引。项目的索引可以改变。映射时使用 item.id 作为键而不是索引。考虑使用指南作为标识。
{product.map((item, idx)=>
<div className='yourCart' key={`cartItem_${item.id}`}> //<-- here
<hr></hr>
<div>
<img src ={item.image}></img>
<h3 className='burgerTitle'>{item.name}</h3>
<h4><strong>$ {item.price}.00</strong></h4>
<Button variant='danger' onClick={()=>removeItem(item.id)}>Remove</Button>
</div>
<br></br>
</div>)}
推荐阅读
- laravel-backpack - 如何添加也使用字体进行显示的字体名称下拉列表,以便用户可以预览字体?
- r - 从 R 中的向量中采样
- python - 将数据框列表添加到字典
- php - 如何显示用户使用 php 选择的日期?
- typescript - 如何使用可选参数重载 TypeScript 中的函数?
- selenium-webdriver - 我正在使用 chrome headless 为 nimo.tv 开发视图机器人,但是当我达到 350 次观看时,我的观看次数重置为 20
- javascript - js RegExp 上的奇怪行为:最后没有捕获一个字符
- python - Pandas - 删除第一列并添加索引
- linux - kubectl exec 的 Keepalive
- kubernetes - minikube 隧道命令在添加路由时显示错误