localstorage.getitem无法更改导航栏的样式

y53ybaqx  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(298)

所以我试图在我使用bootstrap制作的网站中,在明暗主题之间切换。事情进展顺利,但问题是浏览器在刷新网站后无法“记住”它所在的主题,即使它应该在渲染组件时检索主题。

import React, {useState, useEffect} from 'react'
import Link from "next/link"
export default function Navbar() {
    const localTheme = typeof window !== 'undefined' ? localStorage.getItem('theme') : true
    const [theme, setTheme] = useState(localTheme);
    useEffect(() => localStorage.setItem("theme", theme), [theme])
    return (
        <header>
            <nav className={theme ? "navbar navbar-expand-lg bg-light navbar-light py-3" : "navbar navbar-expand-lg bg-dark navbar-dark py-3"}>
                <--Rest of Navbar--!>
                        <div className="form-check form-switch ms-3">
                        <input onClick={() => setTheme(!theme)} className="form-check-input" type="checkbox" id="flexSwitchCheckDefault"/>
                        <label className="form-check-label fw-bold" htmlFor="flexSwitchCheckDefault" style={theme ? {color: "black"} : {color:"white"}}>{theme ? "Light" : "Dark"} Theme</label>
                        </div>
                    </div>                    
                </div>
            </nav>
        </header>

这是一张切换到深色主题后的本地存储图片,它记住了该值,但每当我刷新页面时,导航栏主题就会变亮

wooyq4lh

wooyq4lh1#

这是一个工作示例:

import React, { useState, useEffect } from "react";

const defaultTheme = "light";

export default function Navbar() {
  const localTheme =
    typeof window !== "undefined"
      ? localStorage.getItem("theme") || defaultTheme
      : defaultTheme;

  const [theme, setTheme] = useState(localTheme);
  console.log(`theme`, theme);

  useEffect(() => localStorage.setItem("theme", theme), [theme]);

  return (
    <div>
      <div>Current theme is: {theme}</div>
      <input
        onClick={() => setTheme(theme === "light" ? "dark" : "light")}
        type="checkbox"
        checked={theme === "dark"}
      />
      <label style={theme === "dark" ? { color: "black" } : { color: "white" }}>
        {theme === "light" ? "Light" : "Dark"} Theme
      </label>
    </div>
  );
}

相关问题