日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ahooks封裝cookie?localStorage?sessionStorage方法_React

作者:Gopal ? 更新時間: 2022-09-03 編程語言

引言

本文是深入淺出 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。
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。
  • 如果為函數,則取執行后結果。
  • 否則,直接取值。
// 設置 State
const 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);
    }
  }
};

總結與歸納

原文鏈接:https://juejin.cn/post/7110562564819386398

欄目分類
最近更新