I am trying to switch between components when a button is clicked. The problem is that the state doesn't change. I understand that setState is asynchronous, but it should log the change when I press the button for a second time. Here is my code:
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'));
You are currently assigning a new value to setState
, but setState
is a function you should call:
this.setState({
CurrentState: this.ComponentTwoState
})
You also need to compare against this.state.CurrentState
instead of this.state
in switchState
as shown in this working example .
You're using setState
on the wrong way. It should be used like:
switchState(){
console.log(this.state.CurrentState);
if(this.state === this.ComponentOneState){
this.setState({ CurrentState : this.ComponentTwoState })
}
else{
this.setState({ CurrentState : this.ComponentOneState })
}
}
You should React the docs from React State and Lifecycle , to avoid this kind of mistakes.
There are two corrections :
In switchState
condition check should be
if (this.state.CurrentState === this.ComponentOneState) {
instead if(this.state === this.ComponentOneState){
setState
is a function.Assigning object will not update state.Instead,it should be,
this.setState ( { CurrentState: this.ComponentOneState })
and
this.setState ({ CurrentState : this. ComponentTwoState })
Working codesandbox
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.