繁体   English   中英

setState 没有更新 React Native

[英]setState is not updating React Native

我试图从一个组件中获取 state,但是当我执行 setState() 时,我看不到任何变化。 这是我的 state:

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

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

现在,这里是 function 本身:

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

在这里,在另一个组件中,我称之为 function:

componentDidMount() {

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

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

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

您可以将 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