【问题标题】:ReactJS: Update only specific field in nested state object [duplicate]ReactJS:仅更新嵌套状态对象中的特定字段[重复]
【发布时间】:2018-02-23 18:08:12
【问题描述】:

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

首先我在做:

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

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

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

【问题讨论】:

  • 我认为 React 不是为处理动态字段而设计的。为什么必须使用动态字段?您想尝试替代方案吗?

标签: javascript reactjs


【解决方案1】:

复制this.state[index] 处的对象,并将进度属性替换为新的。

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

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

如果您不支持扩展运算符,可以使用Object.assign

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2020-04-27
    • 2018-11-08
    • 1970-01-01
    • 2019-10-06
    • 2019-02-13
    • 2020-11-13
    相关资源
    最近更新 更多