我需要更新特定对象字段的状态。我的状态是使用动态键值(index
)。
首先我在做:
this.setState({
[index]: {
uploading: uploadInstance,
progress: 0
}
})
现在我只需要更新进度字段。在我的尝试中,uploading
字段丢失了:
this.setState({
[index]: {
progress: progress
}
})
答案 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 });