自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何封裝 Cookie/LocalStorage/SessionStorage Hook?你明白了嗎?

開發(fā) 前端
在使用 updateState 方法的時候,開發(fā)者可以傳入新的 options —— newOptions。會與 useCookieState 設置的 options 進行 merge 操作。最后除了 defaultValue 會透傳給 js-cookie 的 set 方法的第三個參數(shù)。

今天來看看 ahooks 是怎么封裝 cookie/localStorage/sessionStorage 的。

cookie

ahooks 封裝了 useCookieState,一個可以將狀態(tài)存儲在 Cookie 中的 Hook 。

該 hook 使用了 js-cookie[1] 這個 npm 庫。我認為選擇它的理由有以下:

  • 包體積小。壓縮后小于 800 字節(jié)。自身是沒有其它依賴的。這對于原本就是一個工具庫的 ahooks 來講是很重要的。
  • 更好的兼容性。支持所有的瀏覽器。并支持任意的字符。

當然,它還有其他的特點,比如支持 ESM/AMD/CommonJS 方式導入等等。

封裝的代碼并不復雜,先看默認值的設置,其優(yōu)先級如下:

  • 本地 cookie 中已有該值,則直接取。
  • 設置的值為字符串,則直接返回。
  • 設置的值為函數(shù),執(zhí)行該函數(shù),返回函數(shù)執(zhí)行結果。
  • 返回 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 方法的時候,開發(fā)者可以傳入新的 options —— newOptions。會與 useCookieState 設置的 options 進行 merge 操作。最后除了 defaultValue 會透傳給 js-cookie 的 set 方法的第三個參數(shù)。
  • 獲取到 cookie 的值,判斷傳入的值,假如是函數(shù),則取執(zhí)行后返回的結果,否則直接取該值。
  • 如果值為 undefined,則清除 cookie。否則,調(diào)用 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。將狀態(tài)存儲在 localStorage 和 sessionStorage 中的 Hook 。

兩者的使用方法是一樣的,因為官方都是用的同一個方法去封裝的。我們以 useLocalStorageState 為例。

可以看到 useLocalStorageState 其實是調(diào)用 createUseStorageState 方法返回的結果。該方法的入?yún)袛嗍欠駷闉g覽器環(huán)境,以決定是否使用 localStorage,原因在于 ahooks 需要支持服務端渲染。

import { createUseStorageState } from '../createUseStorageState';
import isBrowser from '../utils/isBrowser';

const useLocalStorageState = createUseStorageState(() => (isBrowser ? localStorage : undefined));

export default useLocalStorageState;

我們重點關注一下,createUseStorageState 方法。

  • 先是調(diào)用傳入的參數(shù)。假如報錯會及時 catch。這是因為:

這里返回的 storage 可以看到其實可能是 undefined 的,后面都會有 catch 的處理。

另外,從這個issue[2]中可以看到 cookie 被 disabled 的時候,也是訪問不了 localStorage 的。stackoverflow[3]也有這個討論。(奇怪的知識又增加了)

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 更新的時候執(zhí)行
useUpdateEffect(() => {
setState(getStoredValue());
}, [key]);

最后是更新 storage 的函數(shù):

  • 如果是值為 undefined,則 removeItem,移除該 storage。
  • 如果為函數(shù),則取執(zhí)行后結果。
  • 否則,直接取值。
// 設置 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 的封裝是我們經(jīng)常需要去做的,ahooks 的封裝整體比較簡單,大家可以參考借鑒。

參考資料

[1]js-cookie: https://www.npmjs.com/package/js-cookie[2]

issue: https://github.com/alibaba/hooks/issues/800

[3]stackoverflow: https://stackoverflow.com/questions/26550770/can-session-storage-local-storage-be-disabled-and-cookies-enabled

[4]大家都能看得懂的源碼(一)ahooks 整體架構篇: https://juejin.cn/post/7105396478268407815

[5]如何使用插件化機制優(yōu)雅的封裝你的請求hook : https://juejin.cn/post/7105733829972721677

[6]ahooks 是怎么解決 React 的閉包問題的?: https://juejin.cn/post/7106061970184339464

[7]ahooks 是怎么解決用戶多次提交問題?: https://juejin.cn/post/7106461530232717326

[8]ahooks 中那些控制“時機”的hook都是怎么實現(xiàn)的?: https://juejin.cn/post/7107189225509879838

[9]如何讓 useEffect 支持 async...await?: https://juejin.cn/post/7108675095958126629

[10]如何讓定時器在頁面最小化的時候不執(zhí)行?: https://juejin.cn/post/7109399243202232357

[11]記錄第一次給開源項目提 PR: https://juejin.cn/post/7110144695098933284?

責任編輯:武曉燕 來源: 前端雜貨鋪
相關推薦

2022-02-09 14:47:28

cookie瀏覽器服務器

2022-12-30 08:35:00

2022-10-10 18:38:56

inert屬性鍵盤

2023-12-08 08:38:15

EventLoopAPI瀏覽器

2022-04-07 11:15:22

PulseEventAPI函數(shù)

2023-12-28 08:43:28

前端算法搜索

2024-01-08 20:05:32

2022-10-19 08:19:32

動態(tài)基線預警

2023-06-14 08:15:34

算法合并操作Winner

2023-12-06 08:01:03

CSSPostCSS

2024-03-27 13:33:00

MySQLInnoDB事務

2022-10-24 20:25:40

云原生SpringJava

2022-10-08 08:09:13

MGRGreatSQL事務

2015-09-18 09:17:06

數(shù)據(jù)分析

2022-03-05 17:56:29

桌面應用開發(fā)

2023-01-02 23:58:03

2022-06-07 08:59:58

hookuseRequestReact 項目

2022-07-20 09:06:27

Hook封裝工具庫

2023-11-06 07:37:01

函數(shù)式插槽React

2023-04-04 08:42:30

IT成本技術堆
點贊
收藏

51CTO技術棧公眾號