React-Native:如何在应用程序关闭之前保存数据

Bob*_*bbe 6 react-native asyncstorage react-component

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

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

这是存储数据的功能。

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

我打电话的storeData()方式如下:

componentWillUnmount() {
 console.log("unmount")
 this._storeData();
}
Run Code Online (Sandbox Code Playgroud)

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

Aut*_*cat 3

无法检测应用程序何时在 React-Native 中关闭。

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