Javascript 返回未定义的状态--反应本机
我正在尝试从异步存储中获取值并将其分配给State。 访问URL时,状态值为null/未定义Javascript 返回未定义的状态--反应本机,javascript,reactjs,react-native,ecmascript-6,Javascript,Reactjs,React Native,Ecmascript 6,我正在尝试从异步存储中获取值并将其分配给State。 访问URL时,状态值为null/未定义 constructor(props) { super(props); this.state = { stAccntList: [], stUserAccountNo: '', stCustNo: '', resp: '', }; AsyncStorage.getItem('UserAccountNo').t
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
请告诉我哪里出了问题。是立即使用还是稍后使用
restURL
(即单击事件或稍后使用其他事件)?如果立即使用它,您可能希望在使用restURL之前使用或跟踪AsyncStorage
两者何时都已完成。如果您在以后使用该URL,那么您只需在需要使用它之前完成该URL,或者在使用之前进行检查即可 由于您尝试异步获取数据并更新状态,因此不能保证在执行componentWillMount之前数据可用
您可以在componentDidMount中使用异步等待
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;
}
}
由于您正在尝试异步获取数据并更新状态,在执行componentWillMount之前,不能保证数据可用。如何实现这一点?取决于componentWillMount中restUrl的用途。我将使用该restUrl访问API。我将立即在componentWillMount中的restUrl下面使用该restUrl,然后查看承诺和异步等待。您必须知道这两个异步存储都已完成(触发了它们的
then()
),才能知道数据已返回。