正在删除状态数组中的项

问题描述 投票:1回答:1

我有一个看起来像这样的删除功能:

   this.deleteItem = item => event => {
      const { res, selectedItems } = this.state;
      res.splice(res.indexOf(item), 1);
      selectedItems.splice(res.indexOf(item), 1);

      this.setState({
        res
      });
    };

[此处,res是页面上显示的项目的列表,而selectedItems是其中的那些项目被选择的列表。删除res中的项目时,应更新selectedItems以从列表中删除该项目的索引。

但是,无论何时我尝试删除特定项目,它只会删除添加到数组中的最后一个项目,而不是与单击的目标的索引相对应的项目。必须对其进行索引的方式进行某些操作,但是我一直难以识别源。

我也尝试过参考here,但这没有用,因为我需要将item作为参数。

什么是解决这个问题的好方法?

非常感谢。

javascript arrays reactjs indexing state
1个回答
2
投票

要从数组中取出项目,您可以执行以下操作:

array.filter(item=>item!==itemToRemove)

因此在您的示例中:

this.deleteItem = item => event => {
  this.setState({
    res: this.state.res.filter(r => r !== item),
    selectedItems: this.state.selectedItems.filter(
      s => s !== item
    )
  })
}

如果这不起作用,那么请您用console.log(JSON.stringify(item,undefined,2)记录该项目并同时记录this.state.res,这比我们猜测它们是什么类型要快得多,可以解决您的问题。

为了完成操作,我将添加现代代码以从对象中删除键(请勿在堆栈溢出代码段中尝试使用此键,因为它使用的是古老的babel版本)

const org = {a:1,b:2};
const withoutA = Object.fromEntries(
  Object.entries(org).filter(([key])=>key!=='a')
)
© www.soinside.com 2019 - 2024. All rights reserved.