react-native AsyncStorage 封装

水深无声 2021-08-13 20:51 412阅读 0赞

AsyncStorage 类似localStorage ,不过是异步的 返回Promise

  1. /**
  2. * AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,
  3. */
  4. import { AsyncStorage} from 'react-native';
  5. class StorageUtil {
  6. /**
  7. * 根据key获取json数值
  8. * @param key
  9. * @returns { Promise<TResult>}
  10. */
  11. static get(key) {
  12. return AsyncStorage.getItem(key)
  13. .then(value => {
  14. if (value && value !== '') {
  15. const jsonValue = JSON.parse(value);
  16. return jsonValue;
  17. }
  18. return null;
  19. })
  20. .catch(() => null); } /** * 保存key对应的json数值 * @param key * @param value * @returns {Promise<string>} */ static save(key, value) { return AsyncStorage.setItem(key, JSON.stringify(value));
  21. }
  22. /**
  23. * 更新key对应的json数值
  24. * @param key
  25. * @param value
  26. * @returns { Promise<TResult>|Promise.<TResult>|Promise<T>}
  27. */
  28. static update(key, value) {
  29. return AsyncStorage.get(key).then(item => {
  30. value =
  31. typeof value === 'string' ? value : Object.assign({ }, item, value);
  32. return AsyncStorage.setItem(key, JSON.stringify(value));
  33. });
  34. }
  35. /**
  36. * 删除key对应json数值
  37. * @param key
  38. * @returns { Promise<string>}
  39. */
  40. static deleteItem(key) {
  41. return AsyncStorage.removeItem(key);
  42. }
  43. // 删除选择的json
  44. static deleteOptional(array) {
  45. array.map((item, index) => AsyncStorage.removeItem(item));
  46. }
  47. /**
  48. * 删除所有配置数据
  49. * @returns { Promise<string>}
  50. */
  51. static clear() {
  52. return AsyncStorage.clear();
  53. }
  54. }
  55. export default StorageUtil;

发表评论

表情:
评论列表 (有 0 条评论,412人围观)

还没有评论,来说两句吧...

相关阅读