首页 > web前端 > js教程 > 使用 useCookie Hook 在 React 中管理浏览器 Cookie

使用 useCookie Hook 在 React 中管理浏览器 Cookie

Barbara Streisand
发布: 2025-01-27 16:40:09
原创
348 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板