获取更新状态以保存在React Native中

时间:2019-02-05 12:32:22

标签: reactjs react-native react-native-android

我对本机作出反应还很陌生,我还没有找到解决问题的方法,所以我现在在这里问。我试图在单选按钮的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的异步调用引起的。

0 个答案:

没有答案