我目前在一个天气预报网站工作,我试图应用一个主题切换器。我已经设置了功能,但是在刷新页面时,所选择的主题不会持久。有人能指出我错过了什么吗?console.log显示,当我单击主题切换器时,localStorage中的主题会发生变化。
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;发布于 2022-08-24 01:02:16
您已经将主题从localStorage加载为状态的默认值。localStorage在useEffect中的另一个负载可能是丢弃/重写用户更改。
试着移除它。例如:
useEffect(() => {
localStorage.setItem('theme', theme);
}, [theme]);发布于 2022-08-24 01:02:08
您应该从localStorage加载主题并将其用作initialState,如下所示:
///... 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
发布于 2022-08-24 01:10:19
这里有一个经典的效果钩子无限循环。效果钩子依赖于theme。如果在钩子中调用setTheme,它将无限地重新运行。
我建议创建这样的主题上下文提供程序组件。由于您使用的是类型记录,您应该避免使用any,并正确地键入所有的值。
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>
);
};https://stackoverflow.com/questions/73466324
复制相似问题