本文是深入浅出 ahooks 源码系列文章的第九篇,这个系列的目标主要有以下几点:
今天来看看 ahooks 是怎么封装 cookie/localStorage/sessionStorage 的。
ahooks 封装了 useCookieState,一个可以将状态存储在 Cookie 中的 Hook 。
该 hook 使用了 js-cookie 这个 npm 库。我认为选择它的理由有以下:
当然,它还有其他的特点,比如支持 ESM/AMD/CommonJS 方式导入等等。
封装的代码并不复杂,先看默认值的设置,其优先级如下:
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 值 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;
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。这是因为:
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); } // 代码在后面讲解 }
// 自定义序列化方法 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 的函数:
// 设置 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 的封装整体比较简,以上就是ahooks封装cookie localStorage sessionStorage方法的详细内容,更多关于ahooks封装cookie localStorage sessionStorage的资料请关注其它相关文章!