猿问

反应从对象数组中删除项目

我在本地存储中有一个购物车项目


const cart = [

  {_id: 'abcd1234', productName: 'product1', price: '100'},

  {_id: 'abcd12345', productName: 'product2', price: '200'},

  {_id: 'abcd123456', productName: 'product3', price: '150'},

  {_id: 'abcd1234567', productName: 'product4', price: '175'},

];

并将其映射以显示购物车项目,并使用按钮删除项目


<Container>

      <div>

      {

        cart.map(item => (

        <p>item.productName</p>

        <p>item.price</p>

        <i class="fas fa-trash-alt mr-1" style={{ color: '#ff6b6b' }} onClick={removeProduct}></i>

))

      }

      </div>

</Container>

这是我要删除的功能


  const removeProduct = () => {

    const cart = JSON.parse(localStorage.getItem("cartProduct"));

    let indexToRemove = 1;

    cart.splice(indexToRemove, 1)

    localStorage.setItem("cartProduct", JSON.stringify(cart));

    window.location.reload();

 };

每次我尝试删除一个产品2、产品3或产品4时,删除的是之前的产品。比如我要去掉product4,那么去掉的就是product3。


当只剩一件商品时,根本无法删除。你可以帮帮我吗?谢谢


弑天下
浏览 104回答 2
2回答

30秒到达战场

您需要将当前项目的索引发送给removeProduct函数,以便它知道要删除哪个项目。<Container>&nbsp; <div>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; cart.map((item, index) => ({&nbsp; &nbsp; &nbsp; &nbsp; <p>item.productName</p>&nbsp; &nbsp; &nbsp; &nbsp; <p>item.price</p>&nbsp; &nbsp; &nbsp; &nbsp; <i class="fas fa-trash-alt mr-1" style={{ color: '#ff6b6b' }} onClick={() => this.removeProduct(index)}></i>&nbsp; &nbsp; &nbsp; ))&nbsp; &nbsp; }&nbsp; </div></Container>而在removeProduct功能上,你必须删除该index位置的项目。const removeProduct = (indexToRemove) => {&nbsp; &nbsp; const cart = JSON.parse(localStorage.getItem("cartProduct"));&nbsp; &nbsp; cart.splice(indexToRemove, 1)&nbsp; &nbsp; localStorage.setItem("cartProduct", JSON.stringify(cart));&nbsp; &nbsp; window.location.reload();};

慕婉清6462132

更改 removeproduct 代码如下。并将 product-id 作为参数传递给函数。const removeProduct = (productId) => {&nbsp; &nbsp; let cart = JSON.parse(localStorage.getItem("cartProduct"));&nbsp; &nbsp; cart = cart.filter(productData => productData._id !== productId)&nbsp; &nbsp; localStorage.setItem("cartProduct", JSON.stringify(cart));&nbsp; &nbsp; window.location.reload();&nbsp;};有关filter方法的更多详细信息,请参阅 MDN 文档。如下更改您的组件以将 id 参数传递给函数。<Container>&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; cart.map(item => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p>item.productName</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p>item.price</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; class="fas fa-trash-alt mr-1"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; style={{ color: '#ff6b6b' }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={() => removeProduct(item._id)}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;></i>&nbsp; &nbsp; &nbsp; &nbsp; ))&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; </div></Container>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答