AsyncStorage简析

来源:互联网 发布:对网络直播的利与弊 编辑:程序博客网 时间:2024/06/03 13:57

  今天是8月了,又是很久没有更新日志了呢,这样真是太怠惰了!
  所以今天,笔者就来讲一讲react native中的asyncStorage的大概用法吧~
  记得官方的文档说,asyncStorage最好由使用者自行封装一层再进行使用,因为asyncStorage只支持键值对的存储(key — value),而且这个value只支持字符串的存储……不过这不是还有一个JSON的stringify嘛,其实这个根本算不了什么。

  下面上代码吧,笔者已经将他封装成了一个js模块,用起来还是比较方便的,而且官方文档推荐全局使用一个asyncStorage,所以我们可以在项目的入口处直接使用:

Import DeviceStorage from './util/DeviceStorage';global.Storage = DeviceStorage;

  然后接下来直接用 Storage.save/clear/等等的方法就行啦,并不需要再次import 了!

  附上DeviceStorage的源码。

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 getString(key){        return AsyncStorage.getItem(key).then((value) => {            return value;        });    }    static save(key, value) {        return AsyncStorage.setItem(key, JSON.stringify(value));    }    static saveString(key,value){        return AsyncStorage.setItem(key, 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 clear(key){        return AsyncStorage.removeItem(key).then(val=>{return val;});    }}