javascript - React Native - 无法从 AsyncStorage.getItem() 获取数据
问题描述
我正在使用 AsyncStorage 设置项目并使用 getItem() 方法检索它。我的代码如下:
import React, { Component } from 'react';
import { View } from 'react-native';
import { Container, Left, Title, Header, Body, Right, Content, Text, Button } from 'native-base';
import AsyncStorage from '@react-native-community/async-storage';
class Counter extends Component {
componentDidMount() {
AsyncStorage.setItem('name' , 'abc');
}
getItemData() {
console.log(AsyncStorage.getItem('name'))
}
render() {
return (
<Container>
<Header>
<Left />
<Body>
<Title>Test</Title>
</Body>
<Right />
</Header>
<Content style={{ margin: 8 }}>
<View style={{ flexDirection: "row", alignSelf: "center" }}>
<Button onPress={() => this.getItemData()}><Text> getItem </Text></Button>
</View>
</Content>
</Container>
);
}
}
export default Counter;
但我没有在我的控制台中获得“abc”,而是得到了这个:
{"_U": 0, "_V": 0, "_W": null, "_X": null}
如何在我的控制台中获取“abc”?
解决方案
添加async
和await
:
async getItemData() {
const result = await AsyncStorage.getItem('name');
console.log(result);
}
async componentDidMount() {
await AsyncStorage.setItem('name' , 'abc');
}
推荐阅读
- c# - 在 Linux 中保存文件时出现 System.IO.DirectoryNotFoundException
- angular - 如何强制斯巴达克斯加载模板
- python - 如何使用 Pool 在 Python 中优化多处理
- c - 可变参数函数 64 位 Windows
- fiware - FIWARE的订阅不通知
- google-assistant-sdk - 如何为请求设置自定义位置?
- java - 使用 fx:include 时的自定义控制器工厂
- python-3.x - 由于字符&导致python xml解析错误
- javascript - 我的类别帮助命令运行不正常
- oracle - 如何在 SSIS 中增加 oracle 源中的查询超时