Reputation: 292
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
Upvotes: 0
Views: 78
Reputation: 59491
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});
}
Upvotes: 3