首页 > 解决方案 > 如何从页面中删除数据并且它不显示?

问题描述

当我删除它时,我试图在我的组件中显示新数据,所以我想要做的是,当我删除该数据时,它将不再显示在页面上,但是当我单击按钮时,我有一个错误“购物车。地图不是函数”,我需要您的帮助来告诉我如何在我的页面中显示新数据并修复错误。

useEffect(() => {
    axios.get(url)
    .then(response=>{
        setCart(
            response.data
        );
    })
    .catch(e =>{
        console.log(e);
    })
}, [url])



 const handleDeleteItems = async(key, cart_id) =>{
   var yes = confirm("You are going to remove an item from your cart, are you sure you want to delete item?")

       if(yes===true){
       alert("succefull");
       const temp = [...cart];
       temp.splice(cart_id, 1);
       setCart({
           cart:temp
       });
   }}

这是我的表格,我在其中显示数据,但是当我单击按钮时它给了我一个错误

return (
   <div>
       <Table>
           <thead>
               <tr>
                   <th>Name</th>
                   <th>Price</th>
                   <th>Action</th>
               </tr>
           </thead>
           <tbody>
           {cart.map((cart, key)=>{
               return(
                <tr key={cart.id}>
                <td>{cart.name}</td>
                <td>{cart.price}</td>
                <td>
                    <Button onClick={() => handleDeleteItems(key, cart.id)} variant="danger">Delete</Button>
                </td>
            </tr>
           )})}

           </tbody>
       </Table>
   </div>

标签: reactjsaxiosuse-state

解决方案


首先,如果购物车数据为空或未初始化,您应该添加一个验证以不尝试加载购物车数据。在此示例中,如果购物车为空,我们将显示“尚无产品”。

{cart ? cart.map((cart, key)=>{
               return(
                <tr key={cart.id}>
                <td>{cart.name}</td>
                <td>{cart.price}</td>
                <td>
                    <Button onClick={() => handleDeleteItems(key, cart.id)} variant="danger">Delete</Button>
                </td>
            </tr>
           )}) : <>                     <td>No products yet.</td> 
</>}

推荐阅读