[前端] ahooks封装cookielocalStoragesessionStorage方法

2076 0
Honkers 2022-10-21 16:11:46 | 显示全部楼层 |阅读模式
目录

    引言cookielocalStorage/sessionStorage总结与归纳


引言

本文是深入浅出 ahooks 源码系列文章的第九篇,这个系列的目标主要有以下几点:
    加深对 React hooks 的理解。学习如何抽象自定义 hooks。构建属于自己的 React hooks 工具库。培养阅读学习源码的习惯,工具库是一个对源码阅读不错的选择。
今天来看看 ahooks 是怎么封装 cookie/localStorage/sessionStorage 的。

cookie

ahooks 封装了 useCookieState,一个可以将状态存储在 Cookie 中的 Hook 。
该 hook 使用了 js-cookie 这个 npm 库。我认为选择它的理由有以下:
    包体积小。压缩后小于 800 字节。自身是没有其它依赖的。这对于原本就是一个工具库的 ahooks 来讲是很重要的。更好的兼容性。支持所有的浏览器。并支持任意的字符。
当然,它还有其他的特点,比如支持 ESM/AMD/CommonJS 方式导入等等。
封装的代码并不复杂,先看默认值的设置,其优先级如下:
    本地 cookie 中已有该值,则直接取。设置的值为字符串,则直接返回。设置的值为函数,执行该函数,返回函数执行结果。返回 options 中设置的 defaultValue。
  1. const [state, setState] = useState<State>(() => {
  2.   // 假如有值,则直接返回
  3.   const cookieValue = Cookies.get(cookieKey);
  4.   if (isString(cookieValue)) return cookieValue;
  5.   // 定义 Cookie 默认值,但不同步到本地 Cookie
  6.   // 可以自定义默认值
  7.   if (isFunction(options.defaultValue)) {
  8.     return options.defaultValue();
  9.   }
  10.   return options.defaultValue;
  11. });
复制代码
再看设置 cookie 的逻辑 —— updateState 方法。
    在使用 updateState 方法的时候,开发者可以传入新的 options —— newOptions。会与 useCookieState 设置的 options 进行 merge 操作。最后除了 defaultValue 会透传给 js-cookie 的 set 方法的第三个参数。获取到 cookie 的值,判断传入的值,假如是函数,则取执行后返回的结果,否则直接取该值。如果值为 undefined,则清除 cookie。否则,调用 js-cookie 的 set 方法。最终返回 cookie 的值以及设置的方法。
  1. // 设置 Cookie 值
  2. const updateState = useMemoizedFn(
  3.   (
  4.     newValue: State | ((prevState: State) => State),
  5.     newOptions: Cookies.CookieAttributes = {},
  6.   ) => {
  7.     const { defaultValue, ...restOptions } = { ...options, ...newOptions };
  8.     setState((prevState) => {
  9.       const value = isFunction(newValue) ? newValue(prevState) : newValue;
  10.       // 值为 undefined 的时候,清除 cookie
  11.       if (value === undefined) {
  12.         Cookies.remove(cookieKey);
  13.       } else {
  14.         Cookies.set(cookieKey, value, restOptions);
  15.       }
  16.       return value;
  17.     });
  18.   },
  19. );
  20. return [state, updateState] as const;
复制代码
localStorage/sessionStorage

ahooks 封装了 useLocalStorageState 和 useSessionStorageState。将状态存储在 localStorage 和 sessionStorage 中的 Hook 。
两者的使用方法是一样的,因为官方都是用的同一个方法去封装的。我们以 useLocalStorageState 为例。
可以看到 useLocalStorageState 其实是调用 createUseStorageState 方法返回的结果。该方法的入参会判断是否为浏览器环境,以决定是否使用 localStorage,原因在于 ahooks 需要支持服务端渲染。
  1. import { createUseStorageState } from '../createUseStorageState';
  2. import isBrowser from '../utils/isBrowser';
  3. const useLocalStorageState = createUseStorageState(() => (isBrowser ? localStorage : undefined));
  4. export default useLocalStorageState;
复制代码
我们重点关注一下,createUseStorageState 方法。
先是调用传入的参数。假如报错会及时 catch。这是因为:
    这里返回的 storage 可以看到其实可能是 undefined 的,后面都会有 catch 的处理。另外,从这个 issue 中可以看到 cookie 被 disabled 的时候,也是访问不了 localStorage 的。stackoverflow 也有这个讨论。(奇怪的知识又增加了)
  1. export function createUseStorageState(getStorage: () => Storage | undefined) {
  2.   function useStorageState<T>(key: string, options?: Options<T>) {
  3.     let storage: Storage | undefined;
  4.     // https://github.com/alibaba/hooks/issues/800
  5.     try {
  6.       storage = getStorage();
  7.     } catch (err) {
  8.       console.error(err);
  9.     }
  10.     // 代码在后面讲解
  11. }
复制代码
    支持自定义序列化方法。没有则直接 JSON.stringify。支持自定义反序列化方法。没有则直接 JSON.parse。getStoredValue 获取 storage 的默认值,如果本地没有值,则返回默认值。当传入 key 更新的时候,重新赋值。
  1. // 自定义序列化方法
  2. const serializer = (value: T) => {
  3.   if (options?.serializer) {
  4.     return options?.serializer(value);
  5.   }
  6.   return JSON.stringify(value);
  7. };
  8. // 自定义反序列化方法
  9. const deserializer = (value: string) => {
  10.   if (options?.deserializer) {
  11.     return options?.deserializer(value);
  12.   }
  13.   return JSON.parse(value);
  14. };
  15. function getStoredValue() {
  16.   try {
  17.     const raw = storage?.getItem(key);
  18.     if (raw) {
  19.       return deserializer(raw);
  20.     }
  21.   } catch (e) {
  22.     console.error(e);
  23.   }
  24.   // 默认值
  25.   if (isFunction(options?.defaultValue)) {
  26.     return options?.defaultValue();
  27.   }
  28.   return options?.defaultValue;
  29. }
  30. const [state, setState] = useState<T | undefined>(() => getStoredValue());
  31. // 当 key 更新的时候执行
  32. useUpdateEffect(() => {
  33.   setState(getStoredValue());
  34. }, [key]);
复制代码
最后是更新 storage 的函数:
    如果是值为 undefined,则 removeItem,移除该 storage。如果为函数,则取执行后结果。否则,直接取值。
  1. // 设置 State
  2. const updateState = (value?: T | IFuncUpdater<T>) => {
  3.   // 如果是 undefined,则移除选项
  4.   if (isUndef(value)) {
  5.     setState(undefined);
  6.     storage?.removeItem(key);
  7.     // 如果是function,则用来传入 state,并返回结果
  8.   } else if (isFunction(value)) {
  9.     const currentState = value(state);
  10.     try {
  11.       setState(currentState);
  12.       storage?.setItem(key, serializer(currentState));
  13.     } catch (e) {
  14.       console.error(e);
  15.     }
  16.   } else {
  17.     // 设置值
  18.     try {
  19.       setState(value);
  20.       storage?.setItem(key, serializer(value));
  21.     } catch (e) {
  22.       console.error(e);
  23.     }
  24.   }
  25. };
复制代码
总结与归纳

对 cookie/localStorage/sessionStorage 的封装是我们经常需要去做的,ahooks 的封装整体比较简,以上就是ahooks封装cookie localStorage sessionStorage方法的详细内容,更多关于ahooks封装cookie localStorage sessionStorage的资料请关注中国红客联盟其它相关文章!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4008
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行