如何使用切片更新数组中的对象?

时间:2019-03-12 10:39:59

标签: javascript reactjs

我试图更改数组中on对象的内容,但是没有成功,我尝试使用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
},

1 个答案:

答案 0 :(得分:1)

您可以使用地图和更新来代替切片,

updateRecipient = (newRecipient) => {
    this.setState(prev => ({
      recipients: prev.recipients.map((item) => {
          if (item.email === newRecipient.email) {
              return {...item, ...newRecipient}
          }
          return item;
      })
    }))
  };

使用切片,解决方案变得有点难以阅读,但可以像

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)],
      }
    }))
  };
相关问题