【问题标题】:How to remove the item from the array based on their index如何根据索引从数组中删除项目
【发布时间】:2021-06-18 09:45:32
【问题描述】:
const [data, setData] = useState([
{
 id: null,
 name:  null
},
{
 id: null,
 name: null
},
{
 id: 1,
 name: null
},
{
 id: 2,
 name: null
}
])

如何根据索引删除item?

例如,我有两个数据,每个数据都有删除图标,例如

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

注意:当我尝试使用我这边的过滤器时,它会删除最后一个索引。

【问题讨论】:

  • 在这种情况下,我会使用项目的唯一 ID 而不是数组索引来解决这个问题。
  • @gnujoow 但是如果他们两个是相同的 id 会有问题吗?
  • id代表标识符,id应该是唯一的
  • @charlietfl - 好的。但例如,所有 id 都是 null 并且不是唯一的,或者说没有 id,它只有名称,并且值为 null。有没有其他方法可以删除该项目?

标签: javascript reactjs typescript next.js


【解决方案1】:

您的代码似乎没问题。 你可以试试这个:

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

【讨论】:

【解决方案2】:

你的物品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);
 }
}

它应该可以工作。

猜你喜欢
  • 2021-08-03
  • 1970-01-01
  • 2020-10-19
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2021-12-06
  • 2015-07-19
相关资源
最近更新 更多