本文是深入淺出 ahooks 源碼系列文章的第九篇,該系列已整理成文檔-地址。覺得還不錯,給個 star 支持一下哈,Thanks。 今天來看看 ahooks 是怎麼封裝 cookie/localStorage/sessionStorage 的。 cookie ahooks 封裝了 useCooki ...
本文是深入淺出 ahooks 源碼系列文章的第九篇,該系列已整理成文檔-地址。覺得還不錯,給個 star 支持一下哈,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。
- 如果為函數,則取執行後結果。
- 否則,直接取值。
// 設置 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);
}
}
};
總結與歸納
對 cookie/localStorage/sessionStorage 的封裝是我們經常需要去做的,ahooks 的封裝整體比較簡單,大家可以參考借鑒。
本文已收錄到個人博客中,歡迎關註~