javascript - 状态返回 undefined --React Native

标签 javascript reactjs react-native ecmascript-6

我正在尝试从异步存储中获取值并将其分配给状态。 访问 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;
   }
}

关于javascript - 状态返回 undefined --React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47746977/

相关文章:

javascript - Firebase云函数生成推送ID

javascript - 如何检索在 JavaScript 中触发事件的 html 对象的引用?

javascript - Redux-Toolkit 和 React Hooks - 存储更改不会触发重新渲染

javascript - 如何在 react js 应用程序中插入 hubspot 表单?

react-native - 具有水平滚动和粘性列的 FlatList

javascript - 将几个模块拆分成各自的js文件

php - 在 Javascript 中顺序执行命令

javascript - 在组件内 react :Unable to get this. state.name

android - React Native android 应用程序在一部手机上工作但在另一部手机上崩溃(通过谷歌游戏商店生产)

javascript - 第一次加载应用程序时 React Native 中的全局状态