首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使网站主题持续刷新?

如何使网站主题持续刷新?
EN

Stack Overflow用户
提问于 2022-08-24 00:46:55
回答 3查看 54关注 0票数 1

我目前在一个天气预报网站工作,我试图应用一个主题切换器。我已经设置了功能,但是在刷新页面时,所选择的主题不会持久。有人能指出我错过了什么吗?console.log显示,当我单击主题切换器时,localStorage中的主题会发生变化。

代码语言:javascript
复制
import { WeatherApi } from "./pages/home/weather-api";
import '../src/App.scss'
import { createContext, useEffect, useState } from "react";
import ReactSwitch from "react-switch";

export const ThemeContext = createContext({})

function App() {

  const [theme, setTheme] = useState<string>(localStorage.getItem('theme') || 'light')

  useEffect(() => {

    const localTheme = localStorage.getItem(theme)
    console.log(localTheme)

    if (!localTheme) {
      setTheme("light")
    }

    if (localTheme) {
      if (localTheme === 'light') {
        setTheme('light')
        localStorage.setItem('theme', theme)
        console.log(localStorage)
      }

      if (localTheme === 'dark') {
        setTheme('dark')
        localStorage.setItem('theme', theme)
        console.log(localStorage)
      }
    }
  },[theme])

  const toggleTheme = () => {
    setTheme((currentTheme: any) => (currentTheme === "light" ? "dark" : "light"))
  }

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <div className="App" id={theme}>
        <WeatherApi />
        <div className="switch">
          <label>{theme === "light" ? "Light mode" : "Dark mode"}</label>
          <ReactSwitch onChange={toggleTheme} checked={theme === "dark"} />
        </div>
      </div>
    </ThemeContext.Provider>
  )

}

export default App;
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-08-24 01:02:16

您已经将主题从localStorage加载为状态的默认值。localStorageuseEffect中的另一个负载可能是丢弃/重写用户更改。

试着移除它。例如:

代码语言:javascript
复制
  useEffect(() => {
    localStorage.setItem('theme', theme);
  }, [theme]);
票数 1
EN

Stack Overflow用户

发布于 2022-08-24 01:02:08

您应该从localStorage加载主题并将其用作initialState,如下所示:

代码语言:javascript
复制
///... more js code
  const intialState = localStorage.getItem('theme') || 'light');
  const [theme, setTheme] = useState<string>('')

  const toggleTheme = () => {
    const newTheme = theme === "light" ? "dark" : "light";
    localStorage.setItem('theme', newTheme);
    setTheme(newTheme);
  }
///... more js code

注意:您不需要在字符串中使用JSON.stringify或JSON.parse

票数 1
EN

Stack Overflow用户

发布于 2022-08-24 01:10:19

这里有一个经典的效果钩子无限循环。效果钩子依赖于theme。如果在钩子中调用setTheme,它将无限地重新运行。

我建议创建这样的主题上下文提供程序组件。由于您使用的是类型记录,您应该避免使用any,并正确地键入所有的值。

代码语言:javascript
复制
import { createContext, useState, useEffect, FC } from "react";

type Theme = "light" | "dark";

interface ThemeContextValue {
  theme: Theme;
  toggleTheme: () => void;
}

export const ThemeContext = createContext<ThemeContextValue>({
  theme: "light",
  toggleTheme: () => {},
});

export const ThemeContextProvider: FC = ({ children }) => {
  // initialise state from localStorage
  const [theme, setTheme] = useState<Theme>(
    (localStorage.getItem("theme") ?? "light") as Theme
  );

  // update localStorage when the theme changes
  useEffect(() => {
    localStorage.setItem("theme", theme);
  }, [theme]);

  const toggleTheme = () => {
    setTheme((current) => (current === "light" ? "dark" : "light"));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73466324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档