android - 如何在 React Native 中存储/保存数据

标签 android ios react-native

如何在 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/

相关文章:

reactjs - 即使 flex : 1,React Native 文本输入字段也不会全宽

javascript - 离开页面时 React Native 不运行函数

android - 改造2。响应主体为空

javascript - 如何在 React Native 的 MapView 中设置标记

安卓应用 : text getting cropped on smaller devices

ios - 在azure管道上的InstallAppleCertificate任务中从keyvault检索文件而不是安全文件

ios - 如何通过 UITableViewRowAction swift 使用 inputview

ios - 如何只为 UISearchDisplayController 实现显示一个 TableView

android - Android 下 unity3d 中的 webcamTexture 旋转不同

android - 完全更改包名称,包括公司域