使用 Expo 和 React Native 在应用程序启动之间保留数据

Persisting data between app launches with Expo & React Native

这是我的 App.js,其他都是我能得到的 standard/simple。

import React from 'react';
import { AsyncStorage, Text, View } from 'react-native';

export default class App extends React.Component {
  render() {

    console.log("Fetching data")
    AsyncStorage.getItem('@MySuperStore:key', (value) => {
      console.log("Fetched data: ", value)
      if(value == null) {
        console.log("Writing data!")
        AsyncStorage.setItem('@MySuperStore:key', 'data', () => {
          console.log("Wrote data!")
        })
      }
    })

    return(
    <View>
      <Text>Hello, ReplIt</Text>
    </View>
    );
  }
}

获取的value总是null

我在本地和 ReplIt 上都试过了。在所有情况下,数据不会跨应用程序加载持续存在;我总是看到:

Fetching data
Fetched data:  null
Writing data!
Wrote data!

我做错了什么?我对 Expo 如何与持久存储交互有错误的假设吗? AFAIK,AsyncStorage 应该将内容保存到设备;这样我就可以关闭并重新打开应用程序并保留数据。

试试这些。 AsyncStorage 是一种 Javascript 基于 Promise 的方法。

AsyncStorage.getItem('@MySuperStore:key')
.then(value => console.log(value))

value = await AsyncStorage.getItem('@MySuperStore:key');
console.log(value);

UPD: 我刚刚意识到你的代码按预期工作......可能是评论中提到的 replit 问题。

避免在 render 方法中进行任何请求和异步调用,因为根据 props 或状态的变化,它可能会被调用多次。最好按照 documentation 中的建议将所有相关代码放入 componentDidMount 中。组件挂载时只会调用一次

不确定为什么你的代码对你不起作用,AsyncStorage 允许回调,但是等待对我来说很好:

import React from "react";
import { AsyncStorage, Text, View } from "react-native";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      storedValue: null
    };
  }
  async componentDidMount() {
    let storedValue = await AsyncStorage.getItem("@MySuperStore:key");
    console.log("Fetched data: ", storedValue);
    if (storedValue == null) {
      console.log("Writing data!");
      storedValue = await AsyncStorage.setItem("@MySuperStore:key", "data");
    }
    this.setState({
      storedValue
    });
  }

  render() {
    const { storedValue } = this.state;
    return (
      <View>
        <Text>Hello, ReplIt</Text>
        <Text>This is Stored Value, '{storedValue}'</Text>
      </View>
    );
  }
}