Javascript react';不要更改我的组件的状态
我试图在单击按钮时在组件之间切换。问题是国家没有改变。我知道setState是异步的,但当我第二次按下按钮时,它应该记录更改。这是我的密码:Javascript react';不要更改我的组件的状态,javascript,reactjs,Javascript,Reactjs,我试图在单击按钮时在组件之间切换。问题是国家没有改变。我知道setState是异步的,但当我第二次按下按钮时,它应该记录更改。这是我的密码: class Component1 extends React.Component{ render(){ return <div> Inside ComponentOne</div>; } } class Component2 extends React.Component{ render(){ retu
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'));
类组件1扩展了React.Component{
render(){
返回组件一内;
}
}
类Component2扩展了React.Component{
render(){
返回组件二内;
}
}
类应用程序扩展了React.Component{
ComponentOneState=“ComponentOneState”;
ComponentTwoState=“ComponentTwoState”;
建造师(道具){
超级(道具);
此.state={
CurrentState:this.ComponentOneState
};
this.switchState=this.switchState.bind(this);
}
开关状态(){
console.log(this.state.CurrentState);
if(this.state==this.ComponentOneState){
this.setState={
CurrentState:this.ComponentTwoState
}
}
否则{
this.setState={
CurrentState:this.ComponentOneState
}
}
}
render(){
if(this.state.CurrentState==this.ComponentOneState){
回来
提交
;
}
否则返回
提交
;
}
}
/*
*将上述组件渲染到div#应用程序中
*/
React.render(,document.getElementById('app'));
您当前正在为setState
分配一个新值,但是setState
是一个您应该调用的函数:
this.setState({
CurrentState: this.ComponentTwoState
})
您还需要与
中的this.state.CurrentState
进行比较,而不是中的this.state
,如所示。您使用的设置状态
方法错误。它应该像这样使用:
switchState(){
console.log(this.state.CurrentState);
if(this.state === this.ComponentOneState){
this.setState({ CurrentState : this.ComponentTwoState })
}
else{
this.setState({ CurrentState : this.ComponentOneState })
}
}
您应该对文档做出反应,以避免此类错误。有两个更正:
在开关状态下
应进行状态检查
if (this.state.CurrentState === this.ComponentOneState) {
相反,如果(this.state==this.ComponentOneState){
setState
是一个函数。分配对象不会更新状态。相反,它应该是
this.setState ( {
CurrentState: this.ComponentOneState
})
及
工作setState是一种方法:this.setState({CurrentState:this.ComponentTwoState})
我做了更改,但仍然不起作用。
this.setState ({
CurrentState : this. ComponentTwoState
})