Reputation: 13
I came across this issue working on a project and was able to recreate the issue in this jsfiddle. The state of the parent component seems to be changing when the state of the the child component is updated, what is going on here?
Parent class:
class ParentComponent extends React.Component{
constructor(props){
super(props)
this.state = {objectList:[
{value1:1}
]}
}
render(){
return <div>
{ this.state.objectList.map(object=>{
return <ChildComponent object={object} />
})}
<button onClick={()=>{console.log(this.state.objectList[0].value1)}}>print value</button>
</div>
}
Child class:
class ChildComponent extends React.Component{
constructor(props){
super(props)
this.state = {object:this.props.object}
}
render(){
return <button onClick={()=>{this.updateObject()}}>+1</button>
}
updateObject(){
let object = this.state.object
object.value1+=1
this.setState({object})
}
}
Upvotes: 0
Views: 76
Reputation: 9944
You are mutating the parent state. You should create a whole new object to avoid this problem. Something like this should work:
updateObject(){
let object = {...this.state.object, value1: this.state.object.value1 + 1};
this.setState({object})
}
Upvotes: 1