簡體   English   中英

如何從頁面中刪除數據並且它不顯示?

[英]How can I remove data from the page and it doesn't show?

當我刪除它時,我試圖在我的組件中顯示新數據,所以我想要做的是,當我刪除該數據時,它將不再顯示在頁面上,但是當我單擊按鈕時,我有一個錯誤“購物車。 map 不是一個函數”,我需要你的幫助來告訴我如何在我的頁面中顯示新數據並修復錯誤。

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>

首先,如果購物車數據為空或未初始化,您應該添加一個驗證以不嘗試加載購物車數據。 在此示例中,如果購物車為空,我們將顯示“尚無產品”。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM