vin*_*t O 2 javascript arrays json reactjs react-native
我试图添加和删除数组中的对象,我已经能够找出添加对象部分,但是删除不起作用。我已经使用filter(),但是它什么也没做。现在我正在使用拼接,它可以工作,但是它删除第一个元素,而不是选定的项目。下面是一个示例代码,为了更好地说明,我仅显示了这些功能。
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]
}));
}
Run Code Online (Sandbox Code Playgroud)
我想要
数组中该项的键和索引可能不相同。如果该项在数组中,则可以Array.indexOf()
用来查找其索引,然后将其拼接起来:
handleDelete(item) {
this.setState(({ list }) => {
const newList = [...list];
const index = newList.indexOf(item);
newList.splice(index, 1);
return {
list: newList
};
});
}
Run Code Online (Sandbox Code Playgroud)
或者,如果要使用Array.filter()
,请检查当前元素(o
)的密钥是否不同于item
:
handleDelete(item) {
this.setState(({ list }) => ({
list: list.filter(o => o.key !== item.key)
}))
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27 次 |
最近记录: |