2022年2月更新答案
React native正式反对使用其内置的AsyncStorage
.最新的解决方案是安装it的社区包.
# Install via NPM
npm install --save @react-native-async-storage/async-storage
# ...or install via YARN
yarn add @react-native-async-storage/async-storage
# ...or install via EXPO
expo install @react-native-async-storage/async-storage
实现是这样的
import AsyncStorage from '@react-native-async-storage/async-storage';
const storeKey = '@storage_Key'
const storeData = async (value) => {
try {
await AsyncStorage.setItem(storeKey, value)
} catch (e) {
// saving error
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem(storeKey)
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
老生常谈
有很多 Select ,但最常用的是React Native内置AsyncStorage
.
示例代码
import { AsyncStorage } from "react-native";
const storeKey = 'myPreference';
storeData = async () => {
try {
await AsyncStorage.setItem(storeKey, 'I like to save it.');
} catch (error) {
// Error saving data
}
}
retrieveData = async () => {
try {
const value = await AsyncStorage.getItem(storeKey);
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
阅读https://facebook.github.io/react-native/docs/asyncstorage.html页的更多内容
或者你可以重新考虑第三方库,比如:
https://github.com/kevinresol/react-native-default-preference
https://github.com/mCodex/react-native-sensitive-info