react中的setState函数不会更改组件的状态

时间:2018-07-03 17:49:33

标签: javascript reactjs

我试图在单击按钮时在组件之间切换。问题在于状态不会改变。我知道setState是异步的,但是当我第二次按下按钮时,它应该记录更改。这是我的代码:

class Component1 extends React.Component{
  render(){
    return <div> Inside ComponentOne</div>;
  }
}

class Component2 extends React.Component{
  render(){
    return <div>Inside ComponentTwo</div>;
  }
}

class Application extends React.Component {
  ComponentOneState = "ComponentOneState";
  ComponentTwoState = "ComponentTwoState";
  constructor(props){
     super(props);
     this.state = {
        CurrentState: this.ComponentOneState
     };
    this.switchState = this.switchState.bind(this);
   }

  switchState(){
    console.log(this.state.CurrentState);
    if(this.state === this.ComponentOneState){
      this.setState = {
        CurrentState : this.ComponentTwoState
      }
    }
    else{
      this.setState = {
         CurrentState : this.ComponentOneState
      }
    }
  }

  render() {
    if(this.state.CurrentState === this.ComponentOneState ){
    return <div>
       <Component1 />
       <button onClick = {this.switchState}>Submit</button>
    </div>;
    }
    else return <div>
      <Component2 />
      <button onClick = {this.switchState}>Submit</button>
    </div>;
  }
}

/*
 * Render the above component into the div#app
 */
React.render(<Application />, document.getElementById('app'));

3 个答案:

答案 0 :(得分:1)

您当前正在为setState分配一个新值,但是setState是您应该调用的函数:

this.setState({
  CurrentState: this.ComponentTwoState
})

您还需要与this.state.CurrentState中的this.state进行比较,而不是与this working example中的switchState进行比较。

答案 1 :(得分:0)

您以错误的方式使用setState。它应该像这样使用:

switchState(){
    console.log(this.state.CurrentState);
    if(this.state === this.ComponentOneState){
      this.setState({ CurrentState : this.ComponentTwoState })
    }
    else{
      this.setState({ CurrentState : this.ComponentOneState })
    }
}

您应该对React State and Lifecycle中的文档做出反应,以避免这种错误。

答案 2 :(得分:0)

有两个更正:

  1. switchState中,条件检查应为

    if (this.state.CurrentState === this.ComponentOneState) {
    

代替if(this.state === this.ComponentOneState){

  1. setState是一个函数。分配对象不会更新状态。相反,应该更新状态,

     this.setState ( {
        CurrentState: this.ComponentOneState
     })
    

    this.setState ({
            CurrentState : this. ComponentTwoState
          })
    

工作codesandbox