本文是深入浅出 ahooks 源码系列文章的第九篇,该系列已整顿成文档-地址。感觉还不错,给个 关注 反对一下哈,Thanks。

明天来看看 ahooks 是怎么封装 cookie/localStorage/sessionStorage 的。

cookie

ahooks 封装了 useCookieState,一个能够将状态存储在 Cookie 中的 Hook 。

该 hook 应用了 js-cookie 这个 npm 库。我认为抉择它的理由有以下:

  • 包体积小。压缩后小于 800 字节。本身是没有其它依赖的。这对于本来就是一个工具库的 ahooks 来讲是很重要的。
  • 更好的兼容性。反对所有的浏览器。并反对任意的字符。

当然,它还有其余的特点,比方反对 ESM/AMD/CommonJS 形式导入等等。

封装的代码并不简单,先看默认值的设置,其优先级如下:

  • 本地 cookie 中已有该值,则间接取。
  • 设置的值为字符串,则间接返回。
  • 设置的值为函数,执行该函数,返回函数执行后果。
  • 返回 options 中设置的 defaultValue。
const [state, setState] = useState<State>(() => {  // 如果有值,则间接返回  const cookieValue = Cookies.get(cookieKey);  if (isString(cookieValue)) return cookieValue;  // 定义 Cookie 默认值,但不同步到本地 Cookie  // 能够自定义默认值  if (isFunction(options.defaultValue)) {    return options.defaultValue();  }  return options.defaultValue;});

再看设置 cookie 的逻辑 —— updateState 办法。

  • 在应用 updateState 办法的时候,开发者能够传入新的 options —— newOptions。会与 useCookieState 设置的 options 进行 merge 操作。最初除了 defaultValue 会透传给 js-cookie 的 set 办法的第三个参数。
  • 获取到 cookie 的值,判断传入的值,如果是函数,则取执行后返回的后果,否则间接取该值。
  • 如果值为 undefined,则革除 cookie。否则,调用 js-cookie 的 set 办法。
  • 最终返回 cookie 的值以及设置的办法。
// 设置 Cookie 值const updateState = useMemoizedFn(  (    newValue: State | ((prevState: State) => State),    newOptions: Cookies.CookieAttributes = {},  ) => {    const { defaultValue, ...restOptions } = { ...options, ...newOptions };    setState((prevState) => {      const value = isFunction(newValue) ? newValue(prevState) : newValue;      // 值为 undefined 的时候,革除 cookie      if (value === undefined) {        Cookies.remove(cookieKey);      } else {        Cookies.set(cookieKey, value, restOptions);      }      return value;    });  },);return [state, updateState] as const;

localStorage/sessionStorage

ahooks 封装了 useLocalStorageState 和 useSessionStorageState。将状态存储在 localStorage 和 sessionStorage 中的 Hook 。

两者的应用办法是一样的,因为官网都是用的同一个办法去封装的。咱们以 useLocalStorageState 为例。

能够看到 useLocalStorageState 其实是调用 createUseStorageState 办法返回的后果。该办法的入参会判断是否为浏览器环境,以决定是否应用 localStorage,起因在于 ahooks 须要反对服务端渲染。

import { createUseStorageState } from '../createUseStorageState';import isBrowser from '../utils/isBrowser';const useLocalStorageState = createUseStorageState(() => (isBrowser ? localStorage : undefined));export default useLocalStorageState;

咱们重点关注一下,createUseStorageState 办法。

  • 先是调用传入的参数。如果报错会及时 catch。这是因为:

    • 这里返回的 storage 能够看到其实可能是 undefined 的,前面都会有 catch 的解决。
    • 另外,从这个 issue 中能够看到 cookie 被 disabled 的时候,也是拜访不了 localStorage 的。stackoverflow 也有这个探讨。(奇怪的常识又减少了)
export function createUseStorageState(getStorage: () => Storage | undefined) {  function useStorageState<T>(key: string, options?: Options<T>) {    let storage: Storage | undefined;    // https://github.com/alibaba/hooks/issues/800    try {      storage = getStorage();    } catch (err) {      console.error(err);    }    // 代码在前面解说}
  • 反对自定义序列化办法。没有则间接 JSON.stringify。
  • 反对自定义反序列化办法。没有则间接 JSON.parse。
  • getStoredValue 获取 storage 的默认值,如果本地没有值,则返回默认值。
  • 当传入 key 更新的时候,从新赋值。
// 自定义序列化办法const serializer = (value: T) => {  if (options?.serializer) {    return options?.serializer(value);  }  return JSON.stringify(value);};// 自定义反序列化办法const deserializer = (value: string) => {  if (options?.deserializer) {    return options?.deserializer(value);  }  return JSON.parse(value);};function getStoredValue() {  try {    const raw = storage?.getItem(key);    if (raw) {      return deserializer(raw);    }  } catch (e) {    console.error(e);  }  // 默认值  if (isFunction(options?.defaultValue)) {    return options?.defaultValue();  }  return options?.defaultValue;}const [state, setState] = useState<T | undefined>(() => getStoredValue());// 当 key 更新的时候执行useUpdateEffect(() => {  setState(getStoredValue());}, [key]);

最初是更新 storage 的函数:

  • 如果是值为 undefined,则 removeItem,移除该 storage。
  • 如果为函数,则取执行后后果。
  • 否则,间接取值。
// 设置 Stateconst updateState = (value?: T | IFuncUpdater<T>) => {  // 如果是 undefined,则移除选项  if (isUndef(value)) {    setState(undefined);    storage?.removeItem(key);    // 如果是function,则用来传入 state,并返回后果  } else if (isFunction(value)) {    const currentState = value(state);    try {      setState(currentState);      storage?.setItem(key, serializer(currentState));    } catch (e) {      console.error(e);    }  } else {    // 设置值    try {      setState(value);      storage?.setItem(key, serializer(value));    } catch (e) {      console.error(e);    }  }};

总结与演绎

对 cookie/localStorage/sessionStorage 的封装是咱们常常须要去做的,ahooks 的封装整体比较简单,大家能够参考借鉴。

本文已收录到集体博客中,欢送关注~