我需要一个模态在Next.js网站刷新后坚持

yb3bgrhw  于 2023-08-04  发布在  其他
关注(0)|答案(2)|浏览(119)

我需要使我的模态网站刷新后坚持。一旦用户注销,它就会刷新页面,并且“注销成功”的模态语句消失。我希望模式在退出后显示,并持续到用户单击关闭按钮。我试着使用效果,但我可能用错了,因为我是新的React。

"use client";
import "./signinbutton.css";
import { signIn, signOut, useSession } from "next-auth/react";
import Modal from "./Modal";
import React, { useState } from "react";

import { AiOutlineUserAdd } from "react-icons/ai";
import { IoMdLogOut } from "react-icons/io";

const SigninButton = ({ darkMode }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const { data: session } = useSession();
  console.log(session?.user);

  // Function to open the modal
  function logOut() {
    signOut().then(() => {
      setIsModalOpen(true);
    });
  }

  // Function to close the modal
  function closeModal() {
    setIsModalOpen(false);
  }

  if (session && session.user) {
    return (
      <div>
        <button onClick={logOut} className="profile-button">
          <div className="logout-icon">
            <IoMdLogOut
              size={32}
              color={darkMode ? "#ef9726" : "#0099d8"}
            ></IoMdLogOut>
          </div>
        </button>
        <Modal show={isModalOpen} onClose={closeModal}>
          <h2>Successful Signout</h2>
        </Modal>
      </div>
    );
  }

  return (
    <button onClick={() => signIn()} className="profile-button">
      <div className="user-icon">
        <AiOutlineUserAdd
          size={34}
          color={darkMode ? "#ef9726" : "#0099d8"}
        ></AiOutlineUserAdd>
      </div>
    </button>
  );
};

export default SigninButton;

个字符

dddzy1tm

dddzy1tm1#

如果需要在刷新后保持模式,那么可以使用localStorage来实现。

const KEY = 'SHOW_MODAL';

const Modal = () => {
  const value = localStorage.getItem(KEY);
  const parsedValue = value ? JSON.parse(value) : null;
  
  const [showModal, setShowModal] = useState(parsedValue);

  onClose = () => {
     setShowModal(!showModal);
     localStorage.setItem(KEY, JSON.stringify(false));
  }

  onOpen = () => {
     setShowModal(!showModal);
     localStorage.setItem(KEY, JSON.stringify(true));
  }

  return (showModal ? 
     <div>
       <button onClick={onOpen}>Open</button>
       <button onClick={onClose}>Close</button>
     </div> : null)
}

字符串

4urapxun

4urapxun2#

尝试用如下自定义钩子替换你的useState(代码在Typescript中,但你可以在这里使用JS版本):

export const usePersistentState = <T,>(key: string, initialValue: T) => {
    const [innerState, setInnerState] = React.useState(initialValue);

    React.useEffect(() => {
        const lsValue = localStorage.getItem(key);
        const lsValueParsed = lsValue ? JSON.parse(lsValue) : null;
        if (lsValueParsed) {
            setInnerState(lsValueParsed);
        } else {
            setInnerState(initialValue);
        }
    }, [key, initialValue]);

    return [
        innerState,
        (newValue: T) => {
            setInnerState(newValue);
            localStorage.setItem(key, JSON.stringify(newValue));
        },
    ] as const;
};

字符串

相关问题