javascript - 更新数组 JavaScript 中的字段对象

标签 javascript reactjs

我有一个对象作为数组,存储在变量中

0 : {option: "E", primary: "primary", color: "#4CAF50"}
1 : {option: "B", primary: "primary", color: "#4CAF50"}
2 : {option: "", color: "", primary: ""}
3 : {option: "", color: "", primary: ""}
4 : {option: "", color: "", primary: ""}
5 : {option: "", color: "", primary: ""}

我的问题如何在不进行任何更改的情况下更新特定的关键对象 这是我的代码

handleChange = (index, option) => {

    let navNumber = this.state.navNumber
    navNumber[index] = {
      option:option,
      primary:'primary',
      color:'#4CAF50'
    }

    this.setState({navNumber})

  };

  changeRagu = (index) => { 

    let navNumber = this.state.navNumber    
    navNumber[index] = navNumber[index].color = '#FF9800' 
    this.setState({navNumber})

  }

我想要的只是通过特定的索引更新颜色,而不使所有颜色仍然为空变得相同

最佳答案

这个:

let navNumber = this.state.navNumber

不好,因为您正在复制对 navNumber 变量的引用,而不是创建它的副本。因此,您对 navNumber 所做的任何更改基本上都是对 this.state.navNumber 的更改。这意味着您正在直接改变状态!

试试这个:

changeRagu = (index) => { 
  let navNumber = this.state.navNumber.slice();  //make a copy of navNumber    
  let obj = Object.assign({}, navNumber[index]);  //now copy the object at index
  obj.color = '#FF9800'
  navNumber[index] = obj
  this.setState({navNumber});
}

关于javascript - 更新数组 JavaScript 中的字段对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47153401/

相关文章:

reactjs - 在 NextJS 13.4 API 中抛出错误消息的正确方法是什么? (响应、NextAPI 响应、NextResponse)

javascript - 为什么用户必须在事件(如焦点等)工作之前点击我的应用程序内部?

Javascript 数组洗牌不应输出两个相邻的数组

javascript - react 路由器和 typescript 抛出 "Can' t解析 'react-router-dom'“错误

javascript - 未捕获的类型错误 : Cannot set properties of undefined (setting 'display' )

javascript - 为什么它经历了 if

javascript - 什么是扁平化嵌套对象的简洁 es6 方法?

javascript - 使用 setTimeout 在 Canvas 中设置动画时出现问题

javascript - 无法使用 Mongoose 模型

node.js - Npm启动错误: events. js:292抛出未处理的异常