本文介绍如何在React应用中创建自定义Hook useCookie
,方便地管理浏览器Cookie。我们将构建辅助函数处理Cookie的常用操作:设置、获取和删除。
1. Cookie辅助函数
首先,创建三个函数:setCookie
、getCookie
和removeCookie
。
setCookie
:添加或更新Cookie
export function setCookie(key: string, value: unknown, expiredays = 1): void {
const d = new Date();
d.setTime(d.getTime() + expiredays * 24 * 60 * 60 * 1000);
document.cookie = `${key}=${value}; expires=${d.toUTCString()}; path=/`;
}
该函数接受键、值和过期天数(默认为1天)作为参数,计算过期日期,并创建一个Cookie字符串。
getCookie
:检索Cookie值
export function getCookie(key: string): string | undefined {
const name = `${key}=`;
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return undefined;
}
该函数解码document.cookie
,将Cookie拆分成数组,并搜索指定的键。如果找到,返回对应的值;否则返回undefined
。
removeCookie
:删除Cookie
export function removeCookie(key: string) {
document.cookie = `${key}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;
}
该函数通过设置过期日期为过去的时间来删除Cookie。
2. useCookie
Hook
useCookie
Hook结合了useState
和Cookie辅助函数,提供优雅的Cookie管理方式。
Hook初始化
import { useState } from "react";
import { getCookie, setCookie, removeCookie } from "@/utils/cookie";
export default function useCookie<T>(key: string, initialValue: T) {
const [value, setValue] = useState(() => {
const data = getCookie(key);
return (data || initialValue) as T;
});
// ...additional logic
}
Hook接受Cookie键和初始值作为参数,使用getCookie
获取Cookie的当前值,若不存在则使用初始值。
状态变化处理
function handleDispatch(action: DispatchAction<T>) {
if (typeof action === "function") {
setValue((prevState) => {
const newValue = (action as (prevState: T) => T)(prevState);
setCookie(key, newValue);
return newValue;
});
} else {
setValue(action);
setCookie(key, action);
}
}
handleDispatch
函数更新本地状态和Cookie。如果action
是函数,则应用于当前状态;否则直接设置新值。setCookie
确保浏览器Cookie与状态同步。
清除状态
function clearState() {
removeCookie(key);
setValue(undefined as T);
}
clearState
函数删除Cookie并重置状态。
Hook API返回
return [value, handleDispatch, clearState] as const;
Hook返回一个数组,包含当前值、调度函数和清除函数。
3. 使用useCookie
Hook
示例:
import useCookie from "@/hooks/useCookie";
function ThemeSwitcher() {
const [theme, setTheme, clearTheme] = useCookie<string>("theme", "light");
return (
<div>
<h1>Current Theme: {theme}</h1>
<button onClick={() => setTheme("light")}>Light Mode</button>
<button onClick={() => setTheme("dark")}>Dark Mode</button>
<button onClick={clearTheme}>Clear Theme</button>
</div>
);
}
主题值存储在Cookie中,并在会话中保持。更改主题会更新状态和Cookie。clearTheme
函数重置主题并删除Cookie。
4. 优点
结论
useCookie
Hook简化了React应用中浏览器Cookie的管理,保持类型安全和代码整洁。 它避免了重复的样板代码,使基于Cookie的状态管理更加容易。