反应保存原始取得更新的状态

问题描述 投票:1回答:3

我是很新的原生反应,我并没有发现任何解决我的问题还没有,所以我现在要求在这里。我试图更新单选按钮的onPress事件的值的状态,并保存它之后。问题是,保存越来越不更新值。我知道setState是一个异步调用和forceUpdate是不推荐的解决方案(不工作,我由于某种原因)

这里是一个例子:

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

行为:国家只对第二个呼叫更新

reactjs react-native
3个回答
2
投票

你可以尝试使用setState回调

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

// => { name: "Michael" }

确保状态变化。


0
投票

你是不是有this正确的构造函数结合的处理程序。它应该是

constructor(props) {

/* --- code --- */

this.handleOnPress = this.handleOnPress.bind(this),
this.saveValue = this.saveValue.bind(this)

}


0
投票

做下。

this.setState({
 meter_reading_unit: "someStringValue_false"
}, () => {
 console.log('meter_reading_unit ==> ', this.state.meter_reading_unit); // should be `someStringValue_false`
});

你的下一个渲染更新里面的值someStringValue_false应该可用内的任意位置。

© www.soinside.com 2019 - 2024. All rights reserved.