localStorage 在 React 组件中存储相反的主题值

问题描述 投票:0回答:1

我想将当前主题存储在localStorage中。我正在使用 useEffect 挂钩,它应该存储当前主题,但由于某种原因,它为深色主题存储“light”,为浅色主题存储“dark”。

import { useEffect, useState } from "react";
import "./styles.css";

const ThemeSwitch = () => {
  const [theme, setTheme] = useState("light");
  function changeTheme() {
    setTheme(theme === "light" ? "dark" : "light");
  }
  useEffect(() => {
    localStorage.setItem("Theme", theme);
  }, [theme]);
  return (
    <div className={theme === "light" ? "dark" : "light"} id="container">
      <h1>Hello World!</h1>
      <button
        className={theme === "light" ? "light" : "dark"}
        onClick={changeTheme}
      >
        Change Theme
      </button>
    </div>
  );
};
export default ThemeSwitch;

我预计单击按钮后,将调用函数

changeTheme
,更新主题状态并触发组件的重新渲染。据我所知,在重新渲染期间,localStorage 中的值将被更新。那么为什么它存储相反的值(“亮”表示深色主题,“暗”表示浅色主题)?谢谢你的解释。

reactjs local-storage
1个回答
0
投票

当调用

changeTheme
时,主题状态不会立即更新。相反,React 会安排更新并继续执行后续代码行。因此,当您尝试在调用
localStorage
后立即在
setTheme
中设置项目时,它尚未更新状态。

import { useEffect, useState } from "react";
import "./styles.css";

const ThemeSwitch = () => {
  const [theme, setTheme] = useState("light");

  function changeTheme() {
    const newTheme = theme === "light" ? "dark" : "light";
    setTheme(newTheme);
    localStorage.setItem("Theme", newTheme);
  }

  useEffect(() => {
    //here you must get the theme from localStorage on component mount
    const storedTheme = localStorage.getItem("Theme");
    if (storedTheme) {
      setTheme(storedTheme);
    }
  }, []); // make sure to leave this Empty dependency array to run only once on mount

  return (
    // ... rest of your code
  );
};

export default ThemeSwitch;
© www.soinside.com 2019 - 2024. All rights reserved.