簡體   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