本文示範如何建立自訂 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中文網其他相關文章!