简体   繁体   中英

Update field object inside array javascript

I have an object as array which is store in variable

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: ""}

My question how can I update specific key object without change at all this is my code

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})

  }

All I want is to update only color by specific index without make all color still empty become same

This:

let navNumber = this.state.navNumber

is bad because you are copying the reference to the navNumber variable, rather than creating a copy of it. As a consequence, any changes you do to navNumber is basically a change to this.state.navNumber . This means that you are mutating the state directly!

Instead try this:

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});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM