admin管理员组

文章数量:1303428

I am trying to create a simple shopping cart using ReactJS and I figured a potential way out but whenever I click on the remove button I've set it doesn't really remove the items from the cart.. So those are my state managers right here:

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
    }])

and I have a function that adds the objects in item to the product array, then I have a function that is supposed to remove them that looks like this:

    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()
    }
}

This function is called from here:

                    {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>)}

The problem is that I've tried to use splice, setState, I tried to even clear the entire array and add the elements that are left after applying the filter function to it but it was all to no avail. How can I make it so that when I click on the remove button it removes the specific item from the array??

I am trying to create a simple shopping cart using ReactJS and I figured a potential way out but whenever I click on the remove button I've set it doesn't really remove the items from the cart.. So those are my state managers right here:

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
    }])

and I have a function that adds the objects in item to the product array, then I have a function that is supposed to remove them that looks like this:

    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()
    }
}

This function is called from here:

                    {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>)}

The problem is that I've tried to use splice, setState, I tried to even clear the entire array and add the elements that are left after applying the filter function to it but it was all to no avail. How can I make it so that when I click on the remove button it removes the specific item from the array??

Share asked Sep 26, 2020 at 9:46 Python_Mython79Python_Mython79 1471 gold badge3 silver badges15 bronze badges 3
  • you are mutating state by calling splice directly on it. If this is the route you want to take you can pass a callback to setState setProduct(prevProduct => prevProduct.splice()) – pilchard Commented Sep 26, 2020 at 9:50
  • @pilchard hey thanks for the quick reply !! at first glance it seems to be working, but whenever I add more than one product and click remove on, say the second or the third product, it removes the entire list of products. Why is that? – Python_Mython79 Commented Sep 26, 2020 at 9:53
  • you need to still pass your (idx, 1) to splice, but the answer using id instead is a more robust solution. – pilchard Commented Sep 26, 2020 at 9:55
Add a ment  | 

2 Answers 2

Reset to default 4

You can define removeItem as a function, which gets an id (instead of an index, since that's safer) and setProduct to the subset which should remain. This could be achieved in many ways, in this specific example I use .filter() to find the subset of product whose elements differ in their id from the one that is to be removed and set the result as the new value of product.

removeItem = (id) => {
  setProduct(product.filter((i)=>(i.id !== id)))
 
}

You need to use the mutation method setProduct provided from the useState hook to mutate product state.

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));
    }   
}

usage

<Button variant='danger' onClick={()=>removeItem(item.id)}>Remove</Button>

as a side note:

Consider using definite id values when working with items in an array, instead of index in array. the index of items can change. Use the item.id for a key instead of the index when mapping. Consider using guids as identification.

{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>)}

本文标签: javascriptReactJSHow to remove an item from an array in a functional componentStack Overflow