setState没有更新React Native

时间:2020-05-03 21:47:44

标签: javascript reactjs react-native state

我正在尝试从一个组件获取状态,但是为什么我在执行setState()时看不到任何更改。这是我的状态:

class MyTestComponent extends React.Component {
    constructor(props){
    super(props);

    this.state = {
        check: 'String1'
    }
   this.testOtherFunction = this.testOtherFunction.bind(this);
}

现在,这是函数本身:

   testOtherFunction(){
            this.setState({check: "String2"},
            function(){
               console.log(this.state.check, 'total'); // somewhy is not printed
            });
      return this.state.check;
  }

在这里,在另一个组件中,我将此函数称为:

componentDidMount() {

 console.log("test", MyTestComponent.testOtherFunction()) // returns String1
  }

为什么它从构造函数返回旧状态?我该如何解决?我知道setState是异步的,但我想知道从这种情况下的出路是什么。

1 个答案:

答案 0 :(得分:1)

setState()不会立即更改this.state。调用此方法后访问this.state可能会返回现有值。这就是为什么您可能不会立即看到新值的原因。

您可以将setState与回调函数一起使用。

this.setState({check: "String2"},, function () {
    console.log(this.state.check, 'total');
});