作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
如何在 react native 中存储/保存数据。就像我们在 android 中使用 shared-preference,react native 有什么解决方案吗?我是新手 react 活跃。
please add sample example
最佳答案
您可以使用 React Native AsyncStorage用于将数据存储到设备的本地存储。
import AsyncStorage from '@react-native-async-storage/async-storage';
用这个来保存数据
AsyncStorage.setItem('key', 'value');
AsyncStorage 只接受 string 的值,因此您可能需要在将值设置为 AsyncStorage 之前使用 JSON.stringify()
并检索数据使用
AsyncStorage.getItem('key');
示例代码:
const KEY = 'USER_DATA'
let value = { name: yogi }
AsyncStorage.setItem(KEY, value);
AsyncStorage.getItem(KEY).then(asyncStorageRes => {
console.log(JSON.parse(asyncStorageRes))
});
对于访问 token 、支付信息等敏感数据,您可能希望使用 EncryptedStorage
import EncryptedStorage from 'react-native-encrypted-storage';
它使用与 AsyncStorage 类似的 API,因此您可以使用以下内容来保存和检索数据:
EncryptedStorage.setItem('key', 'value');
EncryptedStorage.getItem('key');
当然还有other storage options也可供选择。
关于android - 如何在 React Native 中存储/保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42945815/
我是一名优秀的程序员,十分优秀!