簡體   English   中英

如何根據索引從數組中刪除項目

[英]How to remove the item from the array based on their index

const [data, setData] = useState([
{
 id: null,
 name:  null
},
{
 id: null,
 name: null
},
{
 id: 1,
 name: null
},
{
 id: 2,
 name: null
}
])

如何根據索引刪除項目?

例如我有兩個數據,每個數據都有刪除圖標,例如

data.map((item, idx) => {
 <label>{id: item.id}</label>
 <label>{name: item.name}</label>
 <button onClick={() => removeItem(idx)}>DELETE</button>
})

const removeItem = (index) => {
 if (data.length > 0) {
  //How to remove the data
   setData(array => data.filter((x, idx) => idx !== index);
 }
}

在我這邊它不起作用,而是當它不等於索引時它會刪除數據。 它刪除最后一個索引。 例如從removeItem(0)它將刪除最后一個索引。 如何解決它。 因為我試圖根據他們的索引刪除項目。

這是示例: https://stackblitz.com/edit/react-hooks-by-example-z5wg3z

注意:當我嘗試使用我這邊的過濾器時,它會刪除最后一個索引。

您的代碼似乎還可以。 你可以試試這個:

const removeItem = (index) => {
 if (data.length > 0) {
  //How to remove the data
  const result = data.filter((x, i) => i !== index);
   setData(result);
  }
}

您的項目 id 不能相同,id 代表標識符,因此您必須使其唯一

data.map((item, idx) => {
  return (
     <div key=`item_{idx}`>
        <label>{id: item.id}</label>
        <label>{name: item.name}</label>
        <button onClick={() => removeItem(item.id)}>DELETE</button>
     </div>
  )
 
})

const removeItem = (itemId) => {
 if (data.length > 0) {
  //How to remove the data
   setData(data => data.filter((item) => item.id !== itemId);
 }
}

它應該使它工作。

暫無
暫無

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

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