簡體   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