首页 > 解决方案 > 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”?

标签: javascriptreactjsreact-native

解决方案


添加asyncawait

    async getItemData() {
       const result = await AsyncStorage.getItem('name');
       console.log(result);
     }

    async componentDidMount() {
       await  AsyncStorage.setItem('name' , 'abc');
     }

推荐阅读