AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。它用来代替LocalStorage。
安装
npm install @react-native-community/async-storage
import AsyncStorage from '@react-native-community/async-storage';
export default class DeviceStorage{
static save = async (key, value) => {
try {
const result = await AsyncStorage.setItem(key, value)
console.log('save result', result)
} catch (e) {
console.log('error',e)
// saving error
}
}
static get = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
//console.log('--value-',value)
return JSON.parse(value);
} catch(e) {
console.log('error',e)
// error reading value
}
}
}
import DeviceStorage from 'xxx/DeviceStorage';
const list = [
{title: 'test1'},
{title: 'test2'}
}
DeviceStorage.save('xxxList',JSON.stringify(list))
componentWillMount=async() => {
const list = await DeviceStorage.get('xxxList')
}