我在反应原生中改变状态值时遇到问题。更改(headerText)的值时。它在方法的第一次调用中不会改变。所以它会显示错误的输出。也许是因为(headerText)的值是基于(索引)值,它将在同一时间发生变化?我怎么解决它?我需要分配一个(索引)值然后赋值(headerText)值
nextRiddle=()=>{
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
//next riddle
if(this.state.index < riddle.length-1){
this.setState({index : this.state.index+1})
this.setState({headerText : (this.state.index+1)});
} else {
this.setState({index : 0}) ;
}
//random color
randomIndexText = 0;
randomIndexButton = 0;
while(randomIndexText == randomIndexButton)
{
randomIndexText = Math.floor((Math.random() * (colorDark.length-1)));
randomIndexButton = Math.floor((Math.random() * (colorDark.length-1)));
}
this.setState({textBGColor : colorDark[randomIndexText]}) ;
this.setState({textColor : colorLight[randomIndexText]}) ;
this.setState({buttonBGColor : colorDark[randomIndexButton]}) ;
this.setState({buttonColor : colorLight[randomIndexButton]}) ;
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
this.setState({titleFont: 45});
//animation for riddle text
if(this.state.animationState==0){
this.state.textFont = 50
this.state.animationState =1;
}else{
this.state.textFont = 45
this.state.animationState =0;
}
}
我怀疑你的问题是由于setState
是异步的。你正在编写上面的代码,期望它是同步的,但事实并非如此。
换句话说,这就是发生的事情:
this.setState({ foo: 'bar' });
this.state.foo; // undefined (or some other previous value).
这就是你需要做的事情(异步):
this.setState({ foo: 'bar' }, () => {
this.state.foo; // 'bar', what we expect it to be.
});
您可能会将一些常见问题合并到现有代码中,但是您需要使用setState
的第二个参数,即回调函数。
我只使用变量而不是状态。它工作正常。