简体   繁体   中英

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

How to delete the item based on the index?

for example I have two data and each data have delete icon for example

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

on my side it doesn't work, instead it will remove the data when its not equal to index. it removes the last index. for example from the removeItem(0) it will remove the last index. how to fix on it. cause I'm trying to remove the item based on their index.

here's the example: https://stackblitz.com/edit/react-hooks-by-example-z5wg3z

NOTE: when I try to use the filter on my side it delete the last index.

Your code seems Ok. Can you try this:

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

Your id for items cannot be the same, id stands for identifier so you have to make it unique

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

It should make it work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM