前端 cookie 使用

1.轻量库下载

go 复制代码
npm install js-cookie
go 复制代码
import Cookies from 'js-cookie';

// 设置(支持对象/过期时间/路径)
Cookies.set('user', { id: 1, role: 'admin' }, { expires: 7, secure: true });

// 读取(自动解析对象)
const user = Cookies.getJSON('user'); // {id:1, role:'admin'}

// 删除
Cookies.remove('user');

3.react中使用

go 复制代码
import Cookies from 'js-cookie';
import { useState, useEffect } from 'react';

function App() {
  const [username, setUsername] = useState('');

  // 设置 Cookie
  const handleSetCookie = () => {
    Cookies.set('username', 'John Doe', { expires: 7 }); // 7天后过期
    setUsername('John Doe');
  };

  // 获取 Cookie
  useEffect(() => {
    const savedUsername = Cookies.get('username');
    if (savedUsername) {
      setUsername(savedUsername);
    }
  }, []);

  // 删除 Cookie
  const handleDeleteCookie = () => {
    Cookies.remove('username');
    setUsername('');
  };

  return (
    <div>
      <p>当前用户名: {username || '未设置'}</p>
      <button onClick={handleSetCookie}>设置 Cookie</button>
      <button onClick={handleDeleteCookie}>删除 Cookie</button>
    </div>
  );
}

4.参数详解

ts 复制代码
Cookies.set(name, value, [options]);
go 复制代码
// 设置 7 天后过期的 Cookie
Cookies.set('token', 'abc123', { expires: 7, path: '/' });

// 存储 JSON 对象
Cookies.set('user', { id: 1, name: 'Alice' });

// 安全 Cookie(HTTPS + 同源严格限制)
Cookies.set('session', 'xyz', { secure: true, sameSite: 'Strict' });
相关推荐
陈随易12 分钟前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
SoaringHeart1 小时前
Flutter进阶:基于 EasyRefresh 的下拉刷新封装 n_easy_refresh_mixin.dart
前端·flutter
IT_陈寒3 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰3 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
山河木马4 小时前
渲染管线-计算得到gl_Position(顶点着色器)之后续GPU流程
javascript·webgl·图形学
竹林8184 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花4 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu12275 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
咪库咪库咪5 小时前
Vue3-生命周期
前端
莪_幻尘6 小时前
你的 AI Skill 越多越蠢?Token 上下文爆炸的求生指南
前端·ai编程