首頁 >web前端 >js教程 >與UseCookie Hook React中管理瀏覽器cookie

與UseCookie Hook React中管理瀏覽器cookie

Barbara Streisand
Barbara Streisand原創
2025-01-27 16:40:09381瀏覽

Managing Browser Cookies in React with useCookie Hook

本文示範如何建立自訂 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>
  • 功能: 接受鍵、值和可選的過期時間(預設為 1 天)。 它會計算過期日期並相應地設定 cookie。
  • 範例: setCookie("theme", "dark", 7); // 設定持續 7 天的 cookie

getCookie:擷取 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"); // 刪除「主題」cookie

2。 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 不存在則預設值)。
  • 狀態初始化:擷取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>
  • 機制: 處理直接值更新和功能更新(用於狀態轉換)。 它確保 cookie 同步。

清除狀態

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>
  • 功能: 刪除 cookie 並將狀態設為 undefined

傳回 Hook 的 API

該鉤子傳回一個陣列:目前值、調度程式函數和清除函數。

<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 鉤子

的優點
  • 簡化的 Cookie 管理: 封裝 cookie 邏輯。
  • 狀態同步:保持 React 狀態和 cookie 同步。
  • 錯誤處理:包含解碼和處理cookie的機制。

結論

useCookie 鉤子簡化了 React 中的 cookie 管理,促進類型安全和乾淨的程式碼。 它簡化了基於 cookie 的狀態管理,消除了重複的程式碼。

以上是與UseCookie Hook React中管理瀏覽器cookie的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn