ReactJS:仅更新嵌套状态对象中的特定字段

时间:2017-09-14 16:46:15

标签: javascript reactjs

我需要更新特定对象字段的状态。我的状态是使用动态键值(index)。

首先我在做:

this.setState({
  [index]: {
    uploading: uploadInstance,
    progress: 0
  }
})

现在我只需要更新进度字段。在我的尝试中,uploading字段丢失了:

this.setState({ 
  [index]: { 
    progress: progress 
  }
})

1 个答案:

答案 0 :(得分:3)

this.state[index]复制对象,并用新的替换progress属性。

const updatedOne = { ...this.state[index], progress: someNewProgress };
this.setState({ [index]: updatedOne });

这样,对象的先前属性将被保留,进度将被替换为新的属性。

如果您不支持点差运营商,可以使用Object.assign

const updatedOne = Object.assign({}, this.state[index], { progress: someNewProgress });