• localStorage封装代码


    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}
    
    • 1
    • 2
    • 3

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

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

    常用场景:

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    封装作用:

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

    使用:

    export enum EStorageKey {
      JOINED_TOUR = 'JOINED_TOUR',
    }
    
    const storageJoinedTours = LocalStorage.read(EStorageKey.JOINED_TOUR);
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    jupyter notebook使用相对路径的方法
    k8s--基础--28.4--ceph--rbd创建和使用
    亚马逊云科技-游戏孵化营 -学习心得
    业务效果提升10%,效率翻倍!PP-OCRv4助力提升政务文档处理能力
    Go学习笔记 -- 数组和切片
    【C++】类和对象(上)
    torchvision.transforms 数据预处理:Normalize()
    Windows平台下OpenCV的编译与安装
    从入门到精通,30天带你学会C++【第七天:for循环和while循环以及数组的学习】(学不会你找我)
    【戴师兄数分】excel基础操作——函数专题(个人笔记)
  • 原文地址:https://blog.csdn.net/cherry__yu/article/details/137432613