0
点赞
收藏
分享

微信扫一扫

Java基础知识总结(42)

今天你读书了吗 04-07 09:00 阅读 2

localStorage封装

JSON.stringfy()和JSON.parse()

JSON.stringfy(): 将 JS 对象转化为 JSON 字符串。

const obj = { name: 'John', age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // {"name":"John","age":30}

JSON.parse(): 将 JSON 字符串转化为 JS 对象,键值都必须使用双引号包裹。

const jsonString = '{"name":"John","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj); // { name: 'John', age: 30 }

常用场景:

  1. 让 localStorage / sessionStorage 可以存储对象。
    localStorage / sessionStorage默认只能存储字符串,实际开发中,我们往往需要存储的数据多为对象类型,此时我们就可以在存储时利用 JSON.stringify() 将对象转为字符串,而在取缓存时,只需 JSON.parse() 转回对象即可。
  2. 实现对象深拷贝。
  3. 与后端 API 通信的时候,通常会接收到 JSON 格式的响应,JSON.parse() 可以将其解析为 JavaScript 对象,方便在客户端进行处理。

localStorage

封装:

export class LocalStorage {
  static read = (key: string) => {
    const readObj = window?.localStorage?.getItem(key);
    try {
      return JSON.parse(readObj);
    } catch (err) {
      console.log(`READ from localStorage "${key}" - `, err);
    }
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  static write = (key: string, value: any) => {
    window?.localStorage?.setItem(key, JSON.stringify(value));
  };

  static remove = (key: string) => {
    window?.localStorage?.removeItem(key);
  };
}

封装作用:

  1. localStorage 只能存字符串类型的数据,在存取的时候封装了 JS 对象和字符串之间转换。
  2. 抽象了操作:通过静态方法的形式,将对存储的读取、写入和删除操作进行了抽象和封装,使得调用方可以直接通过类的静态方法来进行操作,而无需关心底层的实现细节。提高了代码的可读性和可维护性,使得代码结构更加清晰,易于理解和维护。
  3. 提供了异常处理:在读取数据时,对 JSON 解析可能出现的异常进行了捕获和处理,并输出错误日志,避免了因为数据格式不正确而导致的程序崩溃或异常情况。

使用:

export enum EStorageKey {
  JOINED_TOUR = 'JOINED_TOUR',
}

const storageJoinedTours = LocalStorage.read(EStorageKey.JOINED_TOUR);
举报

相关推荐

0 条评论