码迷,mamicode.com
首页 > 其他好文 > 详细

对react native 的AsyncStorage 进行小型封装

时间:2017-06-05 18:58:56      阅读:447      评论:0      收藏:0      [点我收藏+]

标签:ora   lod   param   map   min   array   pair   from   oda   

/**
* @overview A minimalistic wrapper around React Native‘s AsyncStorage.
* @license MIT
*/
import { AsyncStorage } from ‘react-native‘;
import merge from ‘lodash‘;

const store = {
/**
* Get a one or more value for a key or array of keys from AsyncStorage
* @param {String|Array} key A key or array of keys
* @return {Promise}
*/
get(key) {
if(!Array.isArray(key)) {
return AsyncStorage.getItem(key).then(value => {
return JSON.parse(value);
});
} else {
return AsyncStorage.multiGet(key).then(values => {
return values.map(value => {
return JSON.parse(value[1]);
});
});
}
},

/**
* Save a key value pair or a series of key value pairs to AsyncStorage.
* @param {String|Array} key The key or an array of key/value pairs
* @param {Any} value The value to save
* @return {Promise}
*/
save(key, value) {
if(!Array.isArray(key)) {
return AsyncStorage.setItem(key, JSON.stringify(value));
} else {
var pairs = key.map(function(pair) {
return [pair[0], JSON.stringify(pair[1])];
});
return AsyncStorage.multiSet(pairs);
}
},

/**
* Updates the value in the store for a given key in AsyncStorage. If the value is a string it will be replaced. If the value is an object it will be deep merged.
* @param {String} key The key
* @param {Value} value The value to update with
* @return {Promise}
*/
update(key, value) {
return store.get(key).then(item => {
value = typeof value === ‘string‘ ? value : merge({}, item, value);
return AsyncStorage.setItem(key, JSON.stringify(value));
});
},

/**
* Delete the value for a given key in AsyncStorage.
* @param {String|Array} key The key or an array of keys to be deleted
* @return {Promise}
*/
delete(key) {
if (Array.isArray(key)) {
return AsyncStorage.multiRemove(key);
} else {
return AsyncStorage.removeItem(key);
}
},

/**
* Get all keys in AsyncStorage.
* @return {Promise} A promise which when it resolves gets passed the saved keys in AsyncStorage.
*/
keys() {
return AsyncStorage.getAllKeys();
}
};

export default store ;




然后你需要的地方import store 进来就好了。

使用方法
store.save(key,value)
.then(()=>{store.get(key)})
.then(()=>{store.delete(key)})
.catch(error()=>{console.log(error)})

注意在调用时请使用 ansyc await

对react native 的AsyncStorage 进行小型封装

标签:ora   lod   param   map   min   array   pair   from   oda   

原文地址:http://www.cnblogs.com/cielu/p/6946463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!