我尝试使用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中的对象添加到product数组中,然后我有一个函数,应该从中删除它们,看起来像这样:
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,甚至尝试清空整个数组并将过滤函数应用后留下的元素添加到其中,但都没有成功。 当我点击删除按钮时,如何使其从数组中删除特定项?
splice
来改变状态。如果这是您要采取的路线,您可以将回调函数传递给setStatesetProduct(prevProduct => prevProduct.splice())
。 - pilchard(idx, 1)
传递给splice
,但是使用id
而不是它是更健壮的解决方案。 - pilchard