Javascript React Native-无法从AsyncStorage.getItem()获取数据
我使用AsyncStorage设置一个项,并使用getItem()方法检索它。我的代码如下:Javascript React Native-无法从AsyncStorage.getItem()获取数据,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我使用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 '
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”?添加
async
和wait
:
异步getItemData(){
const result=await AsyncStorage.getItem('name');
控制台日志(结果);
}
异步组件didmount(){
等待AsyncStorage.setItem('name','abc');
}
getItem返回一个承诺,该承诺在为给定键找到数据时解析为存储值,否则返回null 读取字符串值:
async getAsyncData() {
await AsyncStorage.getItem('name').then(val => {
if(val !== null) {
console.log(value);
}
})
}
async getAsyncData() {
await AsyncStorage.getItem('name').then(val => {
if(val !== null) {
console.log(JSON.parse(val));
}
})
}
读取对象值:
async getAsyncData() {
await AsyncStorage.getItem('name').then(val => {
if(val !== null) {
console.log(value);
}
})
}
async getAsyncData() {
await AsyncStorage.getItem('name').then(val => {
if(val !== null) {
console.log(JSON.parse(val));
}
})
}
你看过文件了吗?