You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何借助Cookie实现每个用户会话仅显示一次Modal弹窗

方案1:原生Web API实现(无需引入jQuery,更推荐)

React项目没必要为了操作Cookie额外引入jQuery,用原生sessionStorage/localStorage或者原生Cookie操作即可实现需求:

实现逻辑

  • 页面初始化时读取存储标识,判断用户是否已经关闭过弹窗
  • 用户点击关闭时写入存储标识,后续刷新/重新进入页面都不再显示弹窗

代码修改

你可以把状态逻辑封装在Modal组件内部,不用父层传状态,组件独立性更高:

import React, { useEffect, useState } from "react";
import styled from "styled-components";

const Modal = () => {
  // 初始化时从sessionStorage读取是否已关闭的标识,会话级生效
  const [showModal, setShowModal] = useState(() => {
    return sessionStorage.getItem('modal_closed') !== 'true';
  });

  const handleClose = () => {
    setShowModal(false);
    // 写入标识到sessionStorage,会话有效期内都不会再显示
    sessionStorage.setItem('modal_closed', 'true');
  };

  return (
    <>
      {showModal ? (
        <Wrap>
          <TopWrap>
            <h1>IMPORTANT</h1>
            <Close onClick={handleClose}>Close</Close>
          </TopWrap>
          <h3 style={{ fontWeight: "200" }}>
            text here
          </h3>
        </Wrap>
      ) : null}
    </>
  );
};

// 下面的styled组件代码保持不变即可
const Wrap = styled.div`
  position: fixed;
  background: white;
  width: 350px;
  padding: 20px;
  bottom: 2%;
  right: 2%;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 20px;
`;

const TopWrap = styled.div`
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
`;

const Close = styled.h4`
  color: #aaa;
  cursor: pointer;
  margin-bottom: 20px;

  &:hover {
    color: black;
  }
`;
export default Modal;

需求调整说明

  • 如果你需要用户清除Cookie前都不显示弹窗,把代码里的sessionStorage换成localStorage即可,localStorage的存储是持久化的,除非用户主动清除浏览器数据
  • 如果一定要用Cookie存储标识,用原生JS操作也很简单:
    写入Cookie:document.cookie = "modal_closed=true; max-age=31536000; path=/" (max-age单位是秒,这里设置为一年有效)
    读取Cookie:document.cookie.includes('modal_closed=true')
  • 如果你需要保留原来的props结构,由父组件控制显示逻辑,把上面的存储读写逻辑移到父组件操作showModal的位置即可。

方案2:集成jquery.cookie实现(不推荐,仅符合你提到的jQuery方案需求)

如果一定要用jquery.cookie,按以下步骤操作:

  1. 安装依赖:
npm install jquery jquery.cookie
  1. 在组件顶部引入依赖:
import $ from 'jquery';
import 'jquery.cookie';
  1. 替换对应逻辑:
// 初始化状态改成读Cookie
const [showModal, setShowModal] = useState(() => {
  return $.cookie('modal_closed') !== 'true';
});

// 关闭时写Cookie
const handleClose = () => {
  setShowModal(false);
  $.cookie('modal_closed', 'true', { expires: 365, path: '/' }); // expires设有效期天数,path设全站生效
};

内容的提问来源于stack exchange,提问作者aaronbiscotti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 00:09:00