react项目中
使用npm包 umbrella-storage
使用方法和介绍见npm官网,这里做简要分析
// 这个包比较简单 就是类 封装了几个静态方法以供其使用
class umbrella {
static config(prefix: string): void;
static setLocalStorage(key: string, value: any): void;
static getLocalStorage(key: string, withoutParse?: boolean): any;
static removeLocalStorage(key: string): void;
static setSessionStorage(key: string, value: any): void;
static getSessionStorage(key: string, withoutParse?: boolean): any;
static removeSessionStorage(key: string): void;
}
// 下面简要说明这几个静态方法
// config 解决冲突 给key添加(拼接)一个前缀
umbrella.config("REACT-ADMIN");
/**
* setLocalStorage getLocalStorage removeLocalStorage
* 这个方法很大众化了,与存储类似,就是设置值、获取、删除存储的值
* getLocalStorage增加了value解析的功能
*/
umbrella.setLocalStorage("PROJECT_INFOS", {"projectId": "123", "rights": "rm"});
let parseInfos = umbrella.getLocalStorage("PROJECT_INFOS", true);
umbrella.removeLocalStorage("PROJECT_INFOS");
// setSessionStorage getSessionStorage removeSessionStorage 与以上类似
// 总结 就是添加了一个前缀
大众化解决方案
新建一个config.js文件 和utils 文件夹下面新建storage.js文件,摘自osChina
// condig.js
export default {
APP_NAME: 'new-electric-bicycle-web', // 工程名
}
// storage.js
import Config from '../../config'
const prefix = Config.APP_NAME;
export default {
get (key) {
key = `${prefix}-${key}`
let value = localStorage.getItem(key)
if (!value) {
return null
}
return JSON.parse(value)
},
set (key, value) {
key = `${prefix}-${key}`
localStorage.setItem(key, JSON.stringify(value))
},
remove (key) {
key = `${prefix}-${key}`
localStorage.removeItem(key)
},
clear () {
let len = localStorage.length
let keys = []
for (let i = 0; i < len; i++) {
let key = localStorage.key(i)
if (key && key.startsWith(prefix)) {
keys.push(key)
}
}
keys.map(key => localStorage.removeItem(key))
},
}
水平低,若有错误,wang不吝指正。