Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

javascript - 使用splic 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.(现在我正在使用拼接,它可以工作,但是它删除第一个元素,而不是选定的项目。) 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(我想要)   ask by vincent O translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...