如何**在react native中存储/保存数据***。 就像我们在android中使用共享首选项一样,react native有什么解决方案吗?我是react-nactive的新手。*请添加示例
cigdeys31#
您可以使用React Native AsyncStorage将数据存储到设备的本地存储。
import AsyncStorage from '@react-native-async-storage/async-storage';
使用此选项保存数据
AsyncStorage.setItem('key', 'value');
AsyncStorage只接受string形式的值,因此在将该值设置为AsyncStorage之前,可能需要使用JSON.stringify()和检索数据使用
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可供选择。
e5njpo682#
React Native也有共享首选项,这是npm命令获得的:npm install react-native-shared-preferences --save。您可以在此处获得完整的详细信息(如何在react项目中设置它):https://www.npmjs.com/package/react-native-shared-preferences
npm install react-native-shared-preferences --save
2ul0zpep3#
使用异步存储类在react native中存储和检索数据
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})) ]
4条答案
按热度按时间cigdeys31#
您可以使用React Native AsyncStorage将数据存储到设备的本地存储。
使用此选项保存数据
AsyncStorage只接受string形式的值,因此在将该值设置为AsyncStorage之前,可能需要使用
JSON.stringify()
和检索数据使用
示例代码:
对于访问令牌、支付信息等敏感数据,您可能希望使用EncryptedStorage
它使用与AsyncStorage类似的API,因此您可以使用以下命令来保存和检索数据:
当然也有other storage options可供选择。
e5njpo682#
React Native也有共享首选项,这是npm命令获得的:
npm install react-native-shared-preferences --save
。您可以在此处获得完整的详细信息(如何在react项目中设置它):https://www.npmjs.com/package/react-native-shared-preferences2ul0zpep3#
使用异步存储类在react native中存储和检索数据
hmae6n7t4#
你可以使用react-native-easy-app,它比异步存储更容易使用。这个库很棒,它使用异步存储来异步保存数据,并使用内存来同步加载和即时保存数据,所以我们将数据异步保存到内存并在应用程序同步中使用,所以这很棒。