首页 > 解决方案 > 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,我什至尝试清除整个数组并添加在对其应用过滤器函数后留下的元素,但这一切都无济于事。我怎样才能做到这一点,当我单击删除按钮时,它会从数组中删除特定项目?

标签: javascriptarraysreactjslist

解决方案


您需要使用setProductuseState 挂钩提供的突变方法来改变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>)}

推荐阅读