繁体   English   中英

状态返回未定义-反应本机

[英]State Returning Undefined --React Native

我正在尝试从异步存储中获取值并将其分配给State。 访问教to URL时,状态值变为null / undefined

 constructor(props) {
    super(props);
    this.state = {
        stAccntList: [],
        stUserAccountNo: '',
        stCustNo: '',
        resp: '',
    };
    AsyncStorage.getItem('UserAccountNo').then((value) => {
        if (value != '') {
            accno = value;
            this.setState({ stUserAccountNo: value });
           // alert(this.state.stUserAccountNo);
        }
    }).done();
    AsyncStorage.getItem('CustomerNo').then((value) => {

        if (value != '') {
            cusno = value;
            this.setState({ stCustNo: value });
           // alert(this.state.stUserAccountNo);

        }
    }).done();


}


     componentWillMount() {

        let restUrl = urls.URL + this.state.stCustNo + "/" + "accounts" + "/" + this.state.stUserAccountNo;

}

this.state.CustNo和this.state.stUserAccountNo返回null。

请让我知道问题出在哪里。

由于您尝试异步获取数据并更新状态,因此不保证在执行componentWillMount之前数据可用。

您可以在componentDidMount中使用async-await来代替

constructor(props) {
    super(props);
    this.state = {
        stAccntList: [],
        stUserAccountNo: '',
        stCustNo: '',
        resp: '',
    };

}

async componentDidMount() {
   var userAccountNo = await AsyncStorage.getItem('UserAccountNo');
   var CustomerNo = await AsyncStorage.getItem('CustomerNo');
   if (userAccountNo != '') {
        this.setState({ stUserAccountNo: userAccountNo });
   }
   if (CustomerNo != '') {
        this.setState({ stCustNo: CustomerNo });
   }
   if(userAccountNo !== '' && CustomerNo !== '') {
     var restUrl = urls.URL + this.state.stCustNo + "/" + "accounts" + "/" + this.state.stUserAccountNo;
   }
}

restURLrestURL使用还是在以后使用(例如,单击事件或稍后发生的其他事件)? 如果立即使用它,则可能要使用promiseasync等待来跟踪两个AsyncStorage在使用restURL之前已完成的时间。 如果您稍后使用URL,则可以仅在需要使用URL之前就完全依赖它,也可以在使用前进行检查。

暂无
暂无

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

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