如何在react native中存储/保存数据

fkaflof6  于 2022-11-25  发布在  React
关注(0)|答案(4)|浏览(266)

如何**在react native中存储/保存数据***。 就像我们在android中使用共享首选项一样,react native有什么解决方案吗?我是react-nactive的新手。*
请添加示例

cigdeys3

cigdeys31#

您可以使用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))
    });

对于访问令牌、支付信息等敏感数据,您可能希望使用EncryptedStorage

import EncryptedStorage from 'react-native-encrypted-storage';

它使用与AsyncStorage类似的API,因此您可以使用以下命令来保存和检索数据:

EncryptedStorage.setItem('key', 'value');
    EncryptedStorage.getItem('key');

当然也有other storage options可供选择。

e5njpo68

e5njpo682#

React Native也有共享首选项,这是npm命令获得的:npm install react-native-shared-preferences --save。您可以在此处获得完整的详细信息(如何在react项目中设置它):https://www.npmjs.com/package/react-native-shared-preferences

2ul0zpep

2ul0zpep3#

使用异步存储类在react native中存储和检索数据

hmae6n7t

hmae6n7t4#

你可以使用react-native-easy-app,它比异步存储更容易使用。这个库很棒,它使用异步存储来异步保存数据,并使用内存来同步加载和即时保存数据,所以我们将数据异步保存到内存并在应用程序同步中使用,所以这很棒。

export const RNStorage = {// RNStorage : custom data store object
     token: undefined, // string type
     isShow: undefined, // bool type
     userInfo: undefined, // object type
};

import { XStorage } from 'react-native-easy-app';
import { AsyncStorage } from 'react-native';

XStorage.initStorage(RNStorage, AsyncStorage, () => {
    ... // RNStorage 【Property access code snippet】
});

// OR ---------------------------------------------------------------

const result = await XStorage.initStorageSync(RNStorage, AsyncStorage);
if (result) {
    ... // RNStorage 【Property access code snippet】
}

// RNStorage 【Property access code snippet】
// From now on, you can write or read the variables in RNStorage synchronously

console.log(RNStorage.isShow);
// equal to [console.log(await AsyncStorage.getItem('isShow'))] 

RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3==';
// equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ]  

RNStorage.userInfo = {name: 'rufeng', age: 30};
// equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]

相关问题