我在一个项目上遇到了这个问题,并且能够在此jsfiddle中重新创建该问题。当子组件的状态更新时,父组件的状态似乎正在改变,这是怎么回事?
父类:
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>
}
儿童班:
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})
}
}
答案 0 :(得分:2)
您正在更改父状态。您应该创建一个全新的对象以避免此问题。这样的事情应该起作用:
updateObject(){
let object = {...this.state.object, value1: this.state.object.value1 + 1};
this.setState({object})
}