簡體   English   中英

從對象數組中動態刪除項目

[英]Remove Items dynamically from Array of Objects

單擊“刪除”按鈕后,如何從數組中動態刪除 object。

例如,在下面的代碼中,表格有 n 行。 單擊特定的刪除按鈕后,它應該只刪除該行。 就像一個待辦事項列表。

但在我的情況下,整個表都被刪除了。

const [items,itemList]=useState([]);
 const [companyName,setCompanyName]=useState('');
 const [experience, setExperience]=useState();


//Adding Items to Array after clicking "Add" button
const handleClose=()=>{
        itemList((old)=>{
            return [...old,{companyName,experience}]
          })
         
    }
//Removing Items from Array After clicking Remove button
const removeItem=(index)=>{
         
        itemList((old)=>{
          return old.filter((arrEle,i)=>{
            return (
               
                i!==index
                );
          })
        })
   }

//Displaying Array of objects on UI
<Table  striped bordered hover size="sm">
                                <thead>
                                    <tr>
                                        
                                        <th>Company Name</th>
                                        <th>Experience</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    
                                        {
                                            items.map((item,index)=>{

                                                return(
                                                    <tr>
                                                    <td>{item.companyName}</td>
                                                    <td>{item.experience}</td>
                                                    <td><button onClick={()=>{removeItem(index)}}>Remove</button></td>
                                                    </tr>
                                                )
                                            })
                                        }
                                
                                    
                                   
                                </tbody>
                            </Table>

問題

您的代碼中的主要問題是您在表單中呈現了一堆按鈕,並且幾乎所有按鈕都沒有指定按鈕類型。 按鈕的默認值為type="submit" ,因此當其中任何一個被單擊時,它們正在提交表單並且表單正在執行默認提交操作,這也恰好重新加載頁面。 當頁面重新加載您的應用程序重新加載並丟失本地組件 state。

按鈕類型屬性

按鈕的默認行為。 可能的值為:

  • submit :按鈕將表單數據提交到服務器。 如果沒有為與<form>關聯的按鈕指定屬性,或者該屬性為空值或無效值,則這是默認值。
  • reset :該按鈕將所有控件重置為其初始值,例如<input type="reset"> (這種行為往往會惹惱用戶。)
  • button :按鈕沒有默認行為,默認按下時什么也不做。 它可以讓客戶端腳本監聽元素的事件,這些事件在事件發生時觸發。

解決方案

明確指定按鈕類型。

  • 刪除按鈕

     <button type="button" // <-- "button" type onClick={() => { removeItem(item); }} > Remove </button>
  • 提交、重置和打開模式的表單按鈕

     <Button variant="primary" type="submit"> <-- "submit" type Submit </Button> <Button variant="primary" type="reset" // <-- "reset" type style={{ margin: '0 20px' }} > Reset Form </Button> <Button variant="primary" type="button" // <-- "button" type onClick={handleShow} style={{ margin: '0 15px' }} > Add Experience </Button>

注意:提交按鈕仍將提交表單,並且由於您在Form組件上沒有任何onSubmit回調,因此該按鈕將導致頁面重新加載。 您需要添加一個提交處理程序並在onSubmit事件 object 上調用preventDefault

const submitHandler = e => {
  e.preventDefault();
  // handle form data or whatever
};

...

<Form onSubmit={submitHandler}>
  ...

通常我們不應該根據它的索引從數組中刪除任何項目。 因此,請嘗試根據唯一值刪除項目:-

  const removeItem = item => {
    itemList(oldList => {
      return oldList.filter((arrEle, i) => arrEle.companyName !== item.companyName);
    });
  };

並在removeItem function 中傳遞item ,如下所示: -

onClick={() => removeItem(item)}

key添加到tr如下所示:-

<tr key={`${item.companyName}-${index}`}>

工作演示: https://stackblitz.com/edit/react-cxkbge

暫無
暫無

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

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