Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  11] [ 7]  / answers: 1 / hits: 16744  / 9 Years ago, fri, january 22, 2016, 12:00:00
var DENEMEJSON = React.createClass({
getInitialState: function() { return {
arrayone:[{id:1,city:New York},{id:2,city:Brooklyn}],
arraytwo:[{id:101,city:Hamburg},{id:102,city:Schalke}]

}


},
buttonFunc(){
var str=this.state.arrayone;
str[0].city=Tokyo;

this.setState({arrayone:str});
this.setState({arraytwo:str});
},
buttonFunc2(){
var str=this.state.arrayone;
str[0].city=Pakistan;
console.log(JSON.stringify(this.state.arrayone));
console.log(JSON.stringify(this.state.arraytwo));
this.setState({arrayone:str});
},

render: function () {
return ( <div>
<button onClick={this.buttonFunc}/>
<button onClick={this.buttonFunc2}/>
{JSON.stringify(this.state.arrayone)}
{JSON.stringify(this.state.arraytwo)}</div>
)
}//end return

});


When I click the first button the code does what I want. It sets the arrayone[0].city and arraytwo[0].city value to the Tokyo like that.



arrayone : [{id:1,city:Tokyo},{id:2,city:Brooklyn}]



arraytwo : [{id:1,city:Tokyo},{id:2,city:Brooklyn}]



And when I click the second button I only want to set arrayone[0].city value to Pakistan.(not arraytwo).



But the code set both arrayone[0].city and arraytwo[0] value to Pakistan.



Why it sets the arraytwo[0].value to Pakistan?



What can I do to solve this problem?


More From » reactjs

 Answers
6

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/


[#63604] Thursday, January 21, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anyssaarielles

Total Points: 415
Total Questions: 107
Total Answers: 92

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;