本文演示了如何构建自定义 React hook useCookie
,以简化浏览器 cookie 管理。 浏览器 cookie 提供了一种跨会话或应用程序部分存储持久数据的简单方法。
1。 Cookie 实用函数
在创建钩子之前,我们将为常见 cookie 操作定义辅助函数:设置、检索和删除 cookie。
setCookie
:设置或更新 Cookie此函数保存一个键值对,可以选择指定过期时间。
<code class="language-typescript">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=/`; }</code>
setCookie("theme", "dark", 7);
// 设置持续 7 天的 cookiegetCookie
:检索 Cookie 值此函数使用 cookie 的键检索 cookie 的值。
<code class="language-typescript">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; }</code>
document.cookie
,将其拆分为数组,并搜索指定的key。 返回值或 undefined
.const theme = getCookie("theme");
// 检索“主题”值removeCookie
:删除 Cookie此函数通过用空值覆盖 cookie 来删除它,并且不会过期。
<code class="language-typescript">export function removeCookie(key: string): void { document.cookie = `${key}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`; }</code>
removeCookie("theme");
// 删除“主题”cookie2。 useCookie
钩子
useCookie
钩子将实用函数与 React 的 useState
集成,以在组件内进行优雅的 cookie 管理。
<code class="language-typescript">import { useState } from "react"; import { getCookie, setCookie, removeCookie } from "@/utils/cookie"; export default function useCookie<T>(key: string, initialValue: T): [T | undefined, (action: T | ((prevState: T) => T)) => void, () => void] { const [value, setValue] = useState(() => getCookie(key) as T || initialValue); // ...rest of the hook implementation }</code>
key
(cookie key),initialValue
(如果 cookie 不存在则默认值)。initialValue
。handleDispatch
函数会更新状态和 cookie。
<code class="language-typescript"> const handleDispatch = (action: T | ((prevState: T) => 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); } };</code>
clearState
函数删除 cookie 并重置状态。
<code class="language-typescript">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=/`; }</code>
undefined
。该钩子返回一个数组:当前值、调度程序函数和清除函数。
<code class="language-typescript">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; }</code>
3。使用 useCookie
钩子
React 组件中的示例用法:
<code class="language-typescript">export function removeCookie(key: string): void { document.cookie = `${key}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`; }</code>
theme
存储在 cookie 中,跨会话持续存在,并同步更新。 clearTheme
删除 cookie 并重置状态。4。 useCookie
钩子
结论
useCookie
钩子简化了 React 中的 cookie 管理,促进类型安全和干净的代码。 它简化了基于 cookie 的状态管理,消除了重复的代码。
以上是使用 useCookie Hook 在 React 中管理浏览器 Cookie的详细内容。更多信息请关注PHP中文网其他相关文章!