Javascript 在react native中设置状态值
在react native中更改状态值时遇到问题。更改(标题文本)的值时。它不会在方法的第一次调用中更改。因此,它将显示错误的输出。可能是因为(headerText)的值基于(index)值,而该值将同时发生变化?我怎样才能解决它?我需要分配(索引)值,然后分配(标题文本)值Javascript 在react native中设置状态值,javascript,reactjs,react-native,Javascript,Reactjs,React Native,在react native中更改状态值时遇到问题。更改(标题文本)的值时。它不会在方法的第一次调用中更改。因此,它将显示错误的输出。可能是因为(headerText)的值基于(index)值,而该值将同时发生变化?我怎样才能解决它?我需要分配(索引)值,然后分配(标题文本)值 nextridle=()=>{ LayoutImation.configureNext(LayoutImation.Presets.spring); //下一个谜语 if(this.state.index{ this.st
nextridle=()=>{
LayoutImation.configureNext(LayoutImation.Presets.spring);
//下一个谜语
if(this.state.index
我怀疑您的问题是由setState
是异步的这一事实引起的。您在编写上述代码时希望它是同步的,而事实并非如此
换句话说,这就是正在发生的事情:
this.setState({foo:'bar'});
this.state.foo;//未定义(或其他以前的值)。
这就是您需要做的(异步):
this.setState({foo:'bar'},()=>{
this.state.foo;//“bar”,即我们所期望的。
});
将其合并到现有代码中可能会遇到一些一般性问题,但您需要使用
setState
的第二个参数,即回调函数。我怀疑您的问题是由于setState
是异步的。您在编写上述代码时希望它是同步的,而事实并非如此
换句话说,这就是正在发生的事情:
this.setState({foo:'bar'});
this.state.foo;//未定义(或其他以前的值)。
这就是您需要做的(异步):
this.setState({foo:'bar'},()=>{
this.state.foo;//“bar”,即我们所期望的。
});
将其合并到现有代码中可能会遇到一些一般性问题,但您需要使用
setState
的第二个参数,即回调函数。我只是使用变量而不是状态。它工作得很好。我只是使用变量而不是状态。它工作正常。虽然你的答案没有错,但它没有提到setState可以用来更改状态的多个属性,比如:this.setState({textBGColor:colorddark[randomIndexText],textColor:colorLight[randomIndexText],buttonBGColor:colorDark[randomIndexButton],buttonColor:colorLight][randomIndexButton]});
虽然您的答案没有错,但它没有提到setState可以用于更改状态的多个属性,例如:this.setState({textBGColor:colorDark[randomIndexText],textColor:colorLight[randomIndexText],buttonBGColor:colorDark[randomIndexButton],buttonColor:colorLight)[randomIndexButton]});
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;
}
}