简体   繁体   English

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

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

I am trying to add and delete an obect from an array, I have been able to figure out the add object part, but the deletion is not working.我正在尝试从数组中添加和删除一个对象,我已经能够找出添加对象部分,但删除不起作用。 I have used filter() but it did nothing.我使用了 filter() 但它什么也没做。 Now I am using splice, it works but it deletes the first element, instead of the selected item.现在我正在使用 splice,它可以工作,但它会删除第一个元素,而不是所选项目。 below is a sample code, and I have shown only the functions for better clarity.下面是一个示例代码,为了更清晰,我只展示了函数。

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

I would like to我想要

The item's key and index in the array are probably not the same.数组中项目的键和索引可能不相同。 If the item is in the array, you can use Array.indexOf() to find it's index, and splice it out:如果该项目在数组中,则可以使用Array.indexOf()找到它的索引,并将其拼接出来:

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

    return {
      list: newList
    };
  });
}

Or if you want to use Array.filter() , check if the key of of current element ( o ) is different from that of item :或者,如果你想使用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