本文是深入淺出 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 = https://www.cnblogs.com/gopal/archive/2022/08/19/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 = https://www.cnblogs.com/gopal/archive/2022/08/19/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 的封裝整體比較簡單,大家可以參考借鑒,
本文已收錄到個人博客中,歡迎關注~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/502334.html
標籤:其他
