在React中每个会话显示一次modal



我想在每个用户会话中显示一个弹出式模态,我想知道如何在我的React应用程序中合并jquery cookie,以便网站知道用户何时返回,并且在用户的cookie数据被清除之前不会再次显示模态。下面是我的代码:

import React from "react";
import styled from "styled-components";
const Modal = ({ showModal, setShowModal }) => {
return (
<>
{showModal ? (
<Wrap>
<TopWrap>
<h1>IMPORTANT</h1>
<Close onClick={() => setShowModal(false)}>Close</Close>
</TopWrap>
<h3 style={{ fontWeight: "200" }}>
text here
</h3>
</Wrap>
) : null}
</>
);
};
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;

我使用React钩子,所以当用户按下"关闭"文本时,它关闭了模态。我试图解决的问题是,每次刷新页面时都会出现模态,我想每次会话只显示一次。我知道有可能在HTML中使用JQuery做到这一点,但我不确定如何在React中实现这一点。

可以发送一个在用户关闭浏览器会话后过期的cookie。

document.cookie = "showedModal=showedModal; path=/";

在你的代码中你只需要检查cookie是否存在。如果有,就显示模态,如果没有,就不显示。

const useSessionModal = ()=> {
const session = useSession();
const [showModal, setShowModal] = useState(false);
const hideModal = ()=>{
const modalKey = "modalSession";
localStorage.setItem(modalKey, session);
setShowModal(false);
}
useEffect(()=> {
const modalKey = "modalSession";
const modalSession = localStorage.getItem(modalKey);
setShowModal(modalSession!==session);
});
return [showModal, hideModal];
}
const Modal = () => {
const [showModal, hideModal] = useSessionModal();
return (
<>
{showModal ? (
<Wrap>
<TopWrap>
<h1>IMPORTANT</h1>
<Close onClick={hideModal}>Close</Close>
</TopWrap>
<h3 style={{ fontWeight: "200" }}>
text here
</h3>
</Wrap>
) : null}
</>
);
};

在localStorage中保存会话相关标签;

不,兄弟,你不需要jquery, cookie或其他任何东西。所有你需要的是sessionStorage, sessionStorage和localStorage是一样的,但是有一点不同,你在那里存储的东西会在你关闭点击后被删除。

第一个

当你的应用程序加载检查你的sessionStorage

const openend = typeof sessionStorage.getItem("已打开")=== " string "

如果答案是否定的,那么打开模态如果答案是肯定的,那么不要打开

if (openend===false) {

//open modal

}

第二当你的模态是close时,设置open - end

sessionStorage.setItem("打开","1");

最新更新