简体   繁体   English

setState 没有更新 React Native

[英]setState is not updating React Native

I am trying to get state from one component, but somewhy I can't see any changes when I do setState().我试图从一个组件中获取 state,但是当我执行 setState() 时,我看不到任何变化。 Here is my state:这是我的 state:

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

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

Now, here is the function itself:现在,这里是 function 本身:

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

And here, in another component I call this function:在这里,在另一个组件中,我称之为 function:

componentDidMount() {

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

Why it returning old state from a constructor?为什么它从构造函数返回旧的 state? And how can I fix that?我该如何解决? I know setState is async, but I wonder what is the way out from situations like this.我知道 setState 是异步的,但我想知道这种情况的出路是什么。

setState() does not immediately mutate this.state. setState()不会立即改变 this.state。 Accessing this.state after calling this method can potentially return the existing value.在调用此方法后访问 this.state 可能会返回现有值。 That is why you may not see the new value immediately.这就是为什么您可能不会立即看到新值的原因。

you can use setState with callback function.您可以将 setState 与回调 function 一起使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM