由于JSON.parse转化的时候如果遇到非标准JSON的时候经常会报错,所以封装一个工具来实现本地存储,并且封装好一个工具就不用频繁的去写JSON.parse和JSON.stringify来转化JSON和常用数据类型
封装的过程其实就是对本地存储的数据进行判断并且捕获异常。
export const setItem = (key: string, value: object | string | null) => {
if(typeof value === 'object') {
value = JSON.stringify(value)
}
window.sessionStorage.setItem(key,value)
}
export const getItem = (key: string):string | object | null => {
let data = window.sessionStorage.getItem(key)
if(!data) {
return null
}
try {
return JSON.parse(data)
}catch(err) {
return null
}
}