Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过子组件进行反应状态更新_Javascript_Reactjs - Fatal编程技术网

Javascript 通过子组件进行反应状态更新

Javascript 通过子组件进行反应状态更新,javascript,reactjs,Javascript,Reactjs,我在一个项目中遇到了这个问题,并且能够在这个项目中重新创建这个问题。当子组件的状态被更新时,父组件的状态似乎正在改变,这里发生了什么 父类: class ParentComponent extends React.Component{ constructor(props){ super(props) this.state = {objectList:[ {value1:1} ]} } render(){ return <div>

我在一个项目中遇到了这个问题,并且能够在这个项目中重新创建这个问题。当子组件的状态被更新时,父组件的状态似乎正在改变,这里发生了什么

父类:

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>

}
类ParentComponent扩展了React.Component{ 建造师(道具){ 超级(道具) this.state={objectList:[ {value1:1} ]} } render(){ 返回 {this.state.objectList.map(object=>{ 返回 })} {console.log(this.state.objectList[0].value1)}>print value } 儿童班:

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})
}
class-ChildComponent扩展了React.Component{
建造师(道具){
超级(道具)
this.state={object:this.props.object}
}
render(){
返回{this.updateObject()}}>+1
}
updateObject(){
让对象=this.state.object
object.value1+=1
this.setState({object})
}

}您正在改变父状态。您应该创建一个全新的对象来避免此问题。像这样的方法应该会奏效:

updateObject(){
    let object = {...this.state.object, value1: this.state.object.value1 + 1};
    this.setState({object})
}

您正在改变父状态。您应该创建一个全新的对象来避免此问题。像这样的方法应该会奏效:

updateObject(){
    let object = {...this.state.object, value1: this.state.object.value1 + 1};
    this.setState({object})
}

您正在直接修改状态,这是您不应该做的。使用
let object={…this.state.object}相反。除了像已经指出的那样改变状态外,您永远不会将
绑定到组件的instancearrow函数中的
更新对象
,这样您就不必绑定。您直接修改状态,这是不应该做的。使用
let object={…this.state.object}相反。除了像已经指出的那样改变状态外,您永远不会将
绑定到组件的instancearrow函数中的
更新对象
,这样您就不必绑定。为了详细说明,这里有一篇文章介绍了为什么直接改变状态会有问题:TLDR;:直接改变状态不被认为是需要React重新呈现的更改。为了详细说明,这里有一篇文章探讨了为什么直接改变状态是有问题的:TLDR;:直接改变状态不被视为需要React重新渲染的更改。