我需要在 session 之间存储一些用户数据,例如设置、登录、 token 等。尝试了异步存储,但当我重新启动应用程序时,其中的数据被删除。找到了一些引用 keychain 或 NSUserDefaults 的模块,但我不知道哪个模块适合这个目的。
主要特点是即使在应用程序被终止并重新启动后我也可以获得该数据。主要是在 iOS 上,但如果它也能在 Andorid 上,那就太好了。
有人对此有一些经验吗?
编辑:
我尝试使用异步存储。但是当你杀死并重新启动应用程序时它不会做任何事情。
我的存储数据的代码:
AsyncStorage.setItem("prefix", responseData['prefix'])
AsyncStorage.setItem("api_token", responseData['api_token'])
并检索数据:
async _checkAutoLogin(){
var prefix;
var token;
try {
prefix = await AsyncStorage.getItem("prefix");
token = await AsyncStorage.getItem("api_token");
} catch (error) {
AlertIOS.alert('AsyncStorage error: ' + error.message);
}
最佳答案
AsyncStorage 应将您的数据保存到设备,以便您可以访问它,而不管您的应用之前是否已被发送到后台或是否已冷启动。如果您尝试使用 await 关键字,我认为您需要进行一些额外的设置才能使其运行。 Here's a good article让你继续下去。
此外,根据您打算使用 AsyncStorage 执行多少操作,React Native 网站会这样说:
It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.
我围绕它写了一个小包装器,叫做 react-native-simple-store它只是包装 AsyncStorage 并公开一个简约的 API,但默认情况下为您提供 JSON.stringifying 和 JSON.parsing 以获得更复杂的值,因此您不必担心。
或者如果您最终需要更多本地数据库 there are other modules for that .
希望对您有所帮助!
关于android - React-native 在 session 之间存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612646/