AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。它用来代替LocalStorage。
1.封装为DeviceStorage.js类
import { AsyncStorage }from 'react-native'; export default class DeviceStorage{ static get(key) { return AsyncStorage.getItem(key).then((value) => { const jsonValue = JSON.parse(value); return jsonValue; }); } static save(key, value) { return AsyncStorage.setItem(key, JSON.stringify(value)); } static update(key, value) { return DeviceStorage.get(key).then((item) => { value = typeof value === 'string' ? value : Object.assign({}, item, value); return AsyncStorage.setItem(key, JSON.stringify(value)); }); } static delete(key) { return AsyncStorage.removeItem(key); } }
2.使用
2.1 导入DeviceStorage.js
import DeviceStorage from './DeviceStorage';
2.2 保存
DeviceStorage.save("tel","18911112222");
2.3 获取
DeviceStorage.get('tel').then((tel)=>{ if(tel == null || tel == ''){ } else { this.setState({ tel:tel, }); } })
2.4 更新
DeviceStorage.update("tel","17622223333");
2.5 删除
DeviceStorage.delete("tel");