React.js And Update Json Array State
Solution 1:
Your str
is a reference to this.state.arrayone
, and you are setting arraytwo
with str
.
So when arrayone changes, arraytwo changes too.
It's a bad idea to set your str
directly with this.state.arrayone
.
Instead you should clone the state to be able to change what you want to change and update your state ONLY in setState
.
var cloneArrayone = JSON.parse(JSON.stringify(this.state)).arrayone;
cloneArrayone[0].city = "Tokyo";
this.setState({
arrayone: cloneArrayone,
arraytwo: cloneArrayone
});
Here is an example that works: https://jsfiddle.net/snahedis/69z2wepo/28552/
Solution 2:
Your mistake is setting arrayone and arraytwo to THE SAME OBJECT REFERENCE when you click the first button.
buttonFunc(){
var str=this.state.arrayone;
str[0].city="Tokyo";
this.setState({arrayone:str});
this.setState({arraytwo:str});
},
so when you get arrayone and change the object's value
var str=this.state.arrayone;
str[0].city="Pakistan";
You changed both arrayone and arraytwo's referenced object
Solution 3:
The problem occurs when you set both arrayone
and arraytwo
to str
.
this.setState({arrayone:str});
this.setState({arraytwo:str});
When doing this, both are being assigned a reference to the same object, so any changes made to that object will be made to both of them.
One way around this would be to set both of them separately:
var str = this.state.arrayone;
var str2 = this.state.arraytwo;
str[0].city="Tokyo";
str2[0].city="Tokyo";
this.setState({arrayone:str});
this.setState({arraytwo:str2});
Or, you could clone the str
object to make a second, independent copy of it:
var str = this.state.arrayone;
str[0].city="Tokyo";
var strCopy = JSON.parse(JSON.stringify(str));
this.setState({arrayone:str});
this.setState({arraytwo:strCopy});
Post a Comment for "React.js And Update Json Array State"