一旦应用程序离线,React Native AsyncStorage 将停止工作

React Native AsyncStorage stops working once app is offline

我有一个相对简单的应用程序(我的第一个应用程序)需要显示从 GraphQL 查询检索然后存储在 AsyncStorage 中的信息。一切正常,直到您关闭 data/Wifi 连接并重新启动应用程序 - 它不会加载与网络打开时相同的本地数据。这在物理或模拟 Android 设备上是相同的。

除非用户最初设置他们的详细信息,否则没有数据通话。该应用程序是使用 Expo 和 AWS Amplify 2.7.1 版构建的。我在这个最后一期上浪费了几天时间,在 Expo SecureStore 和 Amplify Cache 上得到了同样的行为,我不愿意沿着学习的道路走下去,在这样一个简单的应用程序中包括 Redux...

//import from react native not react
import { AsyncStorage } from 'react-native'

//calling a function as app loads
componentDidMount() {
    this._loadInitialState();
}

//retrieving String from AsyncStorage
_loadInitialState = async () => {
    try {
        const policyNum = await AsyncStorage.getItem('policyNum')
        //...
    } catch {
        //...
    }

//setting state
if (policyNum != null && policyNum != undefined) {
        this.setState({ policyNum: policyNum })
    //...
}

//the original setting of the item
setPolicyDetails = async () => {
    if (this.state.policyNum != null) {
        const policyNumber = this.state.policyNum
        this.state.policyNumSet = true
        try {
            await AsyncStorage.setItem('policyNum', policyNumber)
        } catch (err) { 
        //...
        }
    }
}

你用错了改变状态的事实。

在哪里执行此操作:

    this.state.policyNumSet = true

您应该像这样使用 setState() 函数更改状态:

    this.setState({ policyNumSet: true })

您要存储字符串吗? asyncstorage 只能存储字符串。尝试使用 JSON.stringify 和 JSON.parse

_loadInitialState = async () => {
    try {
        var policyNum = await AsyncStorage.getItem('policyNum')
        policyNum = JSON.parse(policyNum) // converting to original
        //...
    } catch {
        //...
    }

//setting state
if (policyNum != null && policyNum != undefined) {
        this.setState({ policyNum: policyNum })
    //...
}

//the original setting of the item
setPolicyDetails = async () => {
    if (this.state.policyNum != null) {
        const policyNumber = this.state.policyNum
        this.setState({ policyNumSet: true })
        try {
            var policyNumberString = JSON.stringify(policyNumber)
            await AsyncStorage.setItem('policyNum', policyNumberString) //converting to string
        } catch (err) { 
        //...
        }
    }
}

这与外部冲突API