反应本机获取更新状态以进行保存 [英] React native getting updated state for save

查看:33
本文介绍了反应本机获取更新状态以进行保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对原生反应很陌生,我还没有找到任何解决我的问题的方法,所以我现在在这里问.我正在尝试更新单选按钮的 onPress 事件上的值的状态,然后将其保存.问题是保存正在获取未更新的值.我知道 setState 是一个异步调用,而 forceUpdate 不是推荐的解决方案(并且由于某种原因对我不起作用)

I'm quite new to react native and i didn't found any solution to my problem yet so I'm asking here now. I'm trying to update the state of a value on an onPress event of a radio button and save it afterwards. The problem is that the save is getting the non updated value. I know setState is an async call and a forceUpdate is not a recommended solution(and don't work for me for some reason)

这是一个示例:

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> 
    )
  }
}

行为:状态仅在第二次调用时更新

Behavior: the state updates only on the 2nd call

推荐答案

你可以试试用setState回调

setState({ name: "Michael" }, () => console.log(this.state));

// => { name: "Michael" }

确保状态发生变化.

这篇关于反应本机获取更新状态以进行保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆