繁体   English   中英

使用 splice react native 从数组中删除对象元素

[英]deleting object elements from array using splice react native

我正在尝试从数组中添加和删除一个对象,我已经能够找出添加对象部分,但删除不起作用。 我使用了 filter() 但它什么也没做。 现在我正在使用 splice,它可以工作,但它会删除第一个元素,而不是所选项目。 下面是一个示例代码,为了更清晰,我只展示了函数。

        handleDelete(item) {

          this.setState(({ list}) => {
            const newList = [...list];
            newList.splice(item.key, 1);
            console.log('deleted', newList);
            return { list: newList };
          });
        }


        handleAdd() {
          const { firstname, lastname, email, phone} = this.state;
          const ID = uuid();
          const newItemObject = {
              key: ID,
              firstname: firstname,
              lastname: lastname,
              email: email,
              phone: phone,
              image: null,
          };

          this.setState(prevState => ({
            list: [...prevState.list, newItemObject]
          }));
        }

我想要

数组中项目的键和索引可能不相同。 如果该项目在数组中,则可以使用Array.indexOf()找到它的索引,并将其拼接出来:

handleDelete(item) {
  this.setState(({ list }) => {
    const newList = [...list];
    const index = newList.indexOf(item);
    newList.splice(index, 1);

    return {
      list: newList
    };
  });
}

或者,如果你想使用Array.filter()检查的当前元素(关键o )是从不同的item

handleDelete(item) {
  this.setState(({ list }) => ({
    list: list.filter(o => o.key !== item.key)
  }))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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