【问题标题】:React-Native: How to save data before app is closedReact-Native:如何在应用程序关闭之前保存数据
【发布时间】:2019-11-19 04:43:56
【问题描述】:

我正在编写一个 react-native 应用程序,它需要在关闭或后台之前存储一个字符串。当应用程序启动时,它需要再次检索字符串。 (我正在使用 expo 进行开发)

我尝试将数据存储在componentWillUnmount(),但是当我关闭应用程序时该函数没有被调用。

这是存储数据的功能。

_storeData = async () => {
try {
  await AsyncStorage.setItem('data', 'savedData2');
  console.log("done storing");
} catch (error) {
  console.log(error)
}};

我打电话给storeData()如下:

componentWillUnmount() {
 console.log("unmount")
 this._storeData();
}

首先,我认为它不存储数据,因为我在componentWillUnmount() 中调用了一个异步函数,该函数可能在完成之前被取消,但是我也没有收到unmount 日志。

【问题讨论】:

  • 您是否设法使其工作(关闭应用程序时存储数据)?怎么样?

标签: react-native asyncstorage react-component


【解决方案1】:

我有一些适合我的代码。基本上它检查应用程序状态是主动还是被动。即使您使用后退按钮关闭应用程序,也会被动触发。在我的示例中,我正在跟踪用户在我的应用中处于活动或不活动状态的天气。

import React, { useEffect, useRef } from 'react';
import { AppState } from 'react-native';

export default function App(){
    const appState = useRef(AppState.currentState);

    useEffect(()=>{
        fetch()//here I send post request to update users state to active
        
        AppState.addEventListener("change", handleAppStateChange);

        return ()=>{
            AppState.removeEventListener("change", handleAppStateChange);
        }
    },[])

    const handleAppStateChange = (nextAppState) =>{
       if(appState.current.match(/inactive|background/) && nextAppState === "active"){
           fetch()// update users status to inactive
       }
       else{
           fetch()// update users status to active
       }
       appState.current = nextAppState;

    }
}

【讨论】:

    【解决方案2】:

    我正在使用 here 找到的文档中代码的略微修改版本,效果很好。

    在您想要在进入后台时保存数据的组件上,您可以添加如下内容:

    componentDidMount() {
        AppState.addEventListener('change', this._handleAppStateChange);
        this._recoverData();
    }
    
    componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);
    }
    
    _handleAppStateChange = (nextAppState) => {
        if (nextAppState === 'background' || nextAppState === 'inactive') {
            this._storeData('dataToSave');
        }
    };
    

    使用 AppState,您将能够控制应用何时进入后台以及何时再次变为“活动”。

    我在这些代码中调用的 _recoverData 和 _storeData 是使用 AsyncStorage 的异步函数,因此您的方法应该没有问题。

    此外,您可以在文档中找到以下说明:

    此示例只会显示“当前状态为:活动”,因为该应用仅在处于活动状态时对用户可见,而 null 状态只会暂时发生。

    这可能是您没有收到卸载日志的原因(虽然我没有尝试过)。

    【讨论】:

      【解决方案3】:

      如果您使用React Navigation,有一种方法。检查this

      【讨论】:

        【解决方案4】:

        在 react-native 中无法检测应用何时关闭。

        您可以使用 AppState 检测应用何时进入后台,请尝试在文档中查看:https://facebook.github.io/react-native/docs/appstate

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-20
          • 2014-01-11
          • 2020-10-22
          • 1970-01-01
          • 2022-01-17
          • 1970-01-01
          相关资源
          最近更新 更多