我对本机作出反应还很陌生,我还没有找到解决问题的方法,所以我现在在这里问。我试图在单选按钮的onPress
事件上更新值的状态,然后再保存。问题是保存正在获取未更新的值。我知道setState
是异步调用,forceUpdate
不是推荐的解决方案
我conlsole.log handleOnPress
值正确
import RadioForm, {
RadioButton,
RadioButtonInput,
RadioButtonLabel
} from 'react-native-simple-radio-button'
class SomeClass extends Component {
constructor(props) {
super(props)
this.state = {
buttonValues: [{label: "someValue1", value: 0},
{label:"someValue2", value: 1}],
someString: "someStringValue_false"
}
this.handleOnPress = this.handleOnPress.bind(this),
this.saveValue = this.saveValue.bind(this)
}
handleOnPress(value) {
if( value === 1 ){
this.setState({
someString: "someStringValue_true"
})
} else {
this.setState({
someString: "someStringValue_false"
})
}
}
saveValue() {
//no problem in this function tested already in other cases
}
render() {
return(
<View>
<RadioForm
radio_props={this.state.buttonValues}
initial={0}
formHorizontal={true}
labelHorizontal={true}
radioStyle={{paddingRight: 20}}
buttonColor={"red"}
selectedButtonColor = {"green"}
animation={true}
onPress={(value) => this.handleOnPress(value)}
/>
<Button
title={"save"}
onPress={()=> this.saveValue()}
/>
</View>
)
}
}
我希望状态会被设置,但是会保留以前的状态。如果我单击两次按钮是正确的,那么该组件将被重新渲染并且状态发生变化。据我了解,这是由setState
的异步调用引起的。