如果现在有一个需求,是要把用户的账号密码保存到本地,大家会怎么做的呢?如果在android中,我相信一大部分人会想到SharedPreferences,这是一个以键值对的形式进行存储的。那如果在react native中呢,有没有一个像SharedPreferences一样的轻量存储器呢?答案是有的---AsyncStorage。
AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。这是官网上对它的介绍。可以知道,这个asyncstorage也是以键值对的形式进行存储数据的。
那么问题来了,该怎么使用这个呢?官网上说并不推荐我们直接用这个asyncstorage,而是进行抽象封装以后在进行调用。首先看一看我在项目中的用法。
上代码:
import React, { AsyncStorage }from 'react-native'; class DeviceStorage { /** * 获取 * @param key * @returns {Promise<T>|*|Promise.<TResult>} */ static get(key) { return AsyncStorage.getItem(key).then((value) => { const jsonValue = JSON.parse(value); return jsonValue; }); } /** * 保存 * @param key * @param value * @returns {*} */ static save(key, value) { return AsyncStorage.setItem(key, JSON.stringify(value)); } /** * 更新 * @param key * @param value * @returns {Promise<T>|Promise.<TResult>} */ 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)); }); } /** * 更新 * @param key * @returns {*} */ static delete(key) { return AsyncStorage.removeItem(key); } } export default DeviceStorage;
可以看到asyncstorage中存在有更删改查这些方法,当然,上面是把asyncstorage进行了封装,在其他地方调用的时候就可以作为一个工具进行调用了。
调用方式:
Storage.get('appHotSearchTagList').then((tags) => { this.setState({ tags: tags }) });
这里我只是贴出了一种获取数据的方式,其实另外的更新,删除,保存,方式都是差不多。
来源:https://www.cnblogs.com/huangjialin/p/6245122.html
AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。这是官网上对它的介绍。可以知道,这个asyncstorage也是以键值对的形式进行存储数据的。
那么问题来了,该怎么使用这个呢?官网上说并不推荐我们直接用这个asyncstorage,而是进行抽象封装以后在进行调用。首先看一看我在项目中的用法。
上代码:
import React, { AsyncStorage }from 'react-native'; class DeviceStorage { /** * 获取 * @param key * @returns {Promise<T>|*|Promise.<TResult>} */ static get(key) { return AsyncStorage.getItem(key).then((value) => { const jsonValue = JSON.parse(value); return jsonValue; }); } /** * 保存 * @param key * @param value * @returns {*} */ static save(key, value) { return AsyncStorage.setItem(key, JSON.stringify(value)); } /** * 更新 * @param key * @param value * @returns {Promise<T>|Promise.<TResult>} */ 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)); }); } /** * 更新 * @param key * @returns {*} */ static delete(key) { return AsyncStorage.removeItem(key); } } export default DeviceStorage;
可以看到asyncstorage中存在有更删改查这些方法,当然,上面是把asyncstorage进行了封装,在其他地方调用的时候就可以作为一个工具进行调用了。
调用方式:
Storage.get('appHotSearchTagList').then((tags) => { this.setState({ tags: tags }) });
这里我只是贴出了一种获取数据的方式,其实另外的更新,删除,保存,方式都是差不多。
来源:https://www.cnblogs.com/huangjialin/p/6245122.html