網站首頁 編程語言 正文
引言
本文是深入淺出 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
相關推薦
- 2022-05-22 jQuery常用事件方法mouseenter+mouseleave+hover_jquery
- 2021-12-02 Android創建淡入淡出動畫的詳解_Android
- 2022-04-25 python遞歸&迭代方法實現鏈表反轉_python
- 2022-01-10 egg作為后端接口,在前端調用
- 2022-10-06 Django數據映射(一對一,一對多,多對多)_python
- 2022-02-07 SecureCRT連Linux服務器,提示The remote system refused the
- 2022-07-29 Jquery定義對象(閉包)與擴展對象成員的方法_jquery
- 2022-10-16 Python中re模塊:匹配開頭/結尾(^/$)_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支