javascript - 如何使用切片更新数组中的对象?
问题描述
我试图更改数组中对象的内容,但没有成功,我尝试使用 setstate ecc ..
deleteRecipient = () => { //works
this.setState(prev => ({
recipients: [
...prev.recipients.slice(0, this.state.recipientSelectedIndex),
...prev.recipients.slice(this.state.recipientSelectedIndex + 1)
],
recipientsDialogVisible: !prev.recipientsDialogVisible
}))
};
此代码删除特定索引,如何使用相同的代码进行更新?this.state.recipientSelectedIndex 是我保存的索引,例如 2
要更新的数组如下:
newRecipient:{
email: null,
name: null,
notificationType:{ //not this object
SMS: false,
email: false
},//
phone: null
},
解决方案
您可以使用 map 和 update 而不是使用 slice
updateRecipient = (newRecipient) => {
this.setState(prev => ({
recipients: prev.recipients.map((item) => {
if (item.email === newRecipient.email) {
return {...item, ...newRecipient}
}
return item;
})
}))
};
使用 slice 解决方案变得有点难以阅读,但可以作为
updateRecipient = (newRecipient) => {
const idx = this
this.setState(prev => {
return {
recipients: [...prev.recipients.slice(0, prev.recipientSelectedIndex), {...prev.recipients[prev.recipientSelectedIndex], ...newRecipient},
...prev.recipients.slice(prev.recipientSelectedIndex + 1)],
}
}))
};