我正在使用AsyncStorage
in ComponentWillMount
来获取本地存储accessToken
,但它在render()
函数运行后返回promise .如何render()
在承诺完成之前等待?谢谢.
jas*_*ino 64
isLoading
据我所知,你不能等待.我在我正在处理的应用程序中完成的是添加一个加载屏幕,直到AsyncStorage的承诺解决.请参阅以下示例:
//
// With class component syntax
//
import React from 'react';
import {
AsyncStorage,
View,
Text
} from 'react-native';
class Screen extends React.Component {
state = {
isLoading: true
};
componentDidMount() {
AsyncStorage.getItem('accessToken').then((token) => {
this.setState({
isLoading: false
});
});
},
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
// this is the content you want to show after the promise has resolved
return <View/>;
}
}
Run Code Online (Sandbox Code Playgroud)
isLoading
在状态对象上设置属性将导致重新呈现,然后您可以显示依赖于accessToken的内容.
另外,我写了一个名为react-native-simple-store的小库,它简化了AsyncStorage中的数据管理.希望你觉得它有用.
基于react-native doc,您可以执行以下操作:
import React, { Component } from 'react';
import {
View,
} from 'react-native';
let STORAGE_KEY = '@AsyncStorageExample:key';
export default class MyApp extends Component {
constructor(props) {
super(props);
this.state = {
loaded: 'false',
};
}
_setValue = async () => {
try {
await AsyncStorage.setItem(STORAGE_KEY, 'true');
} catch (error) { // log the error
}
};
_loadInitialState = async () => {
try {
let value = await AsyncStorage.getItem(STORAGE_KEY);
if (value === 'true'){
this.setState({loaded: 'true'});
} else {
this.setState({loaded: 'false'});
this._setValue();
}
} catch (error) {
this.setState({loaded: 'false'});
this._setValue();
}
};
componentWillMount() {
this._loadInitialState().done();
}
render() {
if (this.state.loaded === 'false') {
return (
<View><Text>Loading...</Text></View>
);
}
return (
<View><Text>Main Page</Text></View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22834 次 |
最近记录: |