[英]What is the proper/right way to use Async Storage?
I am a react-native newbie. 我是一名反应型新手。
I'm trying to use Async Storage in my application. 我正在尝试在应用程序中使用异步存储。 I want the async storage to store token when user log in, it will navigate to homescreen.
我希望异步存储在用户登录时存储令牌,它将导航到主屏幕。 At homescreen, im trying to get the token through async storage and print it on console but all i get is promise.
在主屏幕上,即时消息试图通过异步存储获取令牌并将其打印在控制台上,但我得到的只是承诺。 I just want to know what is the proper way to use Async storage especially in storing token?
我只想知道使用异步存储的正确方法是什么,尤其是在存储令牌时? I know the alternative for this problem is using Redux state management, but I'm trying to learn the basic method.
我知道解决此问题的替代方法是使用Redux状态管理,但是我正在尝试学习基本方法。
I've tried to store the token in a variable in ComponentWillMount(), but it still does not work. 我试图将令牌存储在ComponentWillMount()中的变量中,但仍然无法正常工作。
class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {
token = getToken();
}
render() {
const { navigate } = this.props.navigation;
console.log(token);
return (
<View style={styles.container}>
<Text> HomeScreen </Text>
</View>
);
}
}
const getToken = async () => {
let token = "";
try {
token = await AsyncStorage.getItem("token");
} catch (error) {
console.log(error);
}
return token;
};
First, I should note that componentWillMount
is deprecated and you can use constructor
or componentDidMount
instead. 首先,我要指出,
componentWillMount
被弃用,你可以使用constructor
或componentDidMount
代替。
if you log token in getToken
and after getting it, it will work fine. 如果您在
getToken
登录令牌,并且在获取令牌后,它将可以正常工作。 if you want to check if the user is logged in, you can do like this 如果要检查用户是否已登录,可以这样做
constructor(props) {
super(props);
this.state = {};
getToken().then((token)=>{
console.log(token)
//check if user is logged in
})
}
or you can do this in componentDidMount
. 或者您可以在
componentDidMount
执行此操作。 I hope this can help you 希望对您有所帮助
You should use it something like this, 你应该用这样的东西
import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native';
//for storing Data
setName = (value) => {
AsyncStorage.setItem('name', value);
this.setState({ 'name': value });
}
//for Retrieving Data
componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))
Here it is another simple example . 这是另一个简单的例子 。
Try to use it with Async and await 尝试将其与Async结合使用并等待
setValue: function (key, value) {
AsyncStorage.setItem(key, value)
},
getValue: async (key) => {
let value = '';
try {
value = await AsyncStorage.getItem(key) || 'none';
} catch (error) {
// Error retrieving data
console.log(error.message);
}
return value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.