解决方法:每次渲染后,从 React Hook useEffect 内部对 'theme' 变量的赋值将丢失



我是React的新手,我正在研究一个暗模式函数。它有一个警告,我想问一下修复它的最好方法是什么。由于

20:21  warning  Assignments to the 'theme' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store
it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect
import React from "react";
import { RiContrastLine } from 'react-icons/ri';
import { useEffect } from "react";

const DarkMode = () => {
let body = "";
if (typeof document !== "undefined") {
body = document.body;
}
let clickedClass = "clicked";
const lightTheme = "light-mode";
const darkTheme = "dark-mode";
let theme;
useEffect(() => {
if (localStorage) {
theme = localStorage.getItem("theme");
if (theme === darkTheme) {
}
}
if (theme === lightTheme || theme === darkTheme) {
body.classList.add(theme);
} else {
body.classList.add(lightTheme);
}
}, [])
const switchTheme = (e) => {
if (theme === darkTheme) {
body.classList.replace(darkTheme, lightTheme);
localStorage.setItem("theme", "light-mode");
e.target.classList.remove(clickedClass);
theme = lightTheme;
} else {
body.classList.replace(lightTheme, darkTheme);
localStorage.setItem("theme", "dark-mode");
e.target.classList.add(clickedClass);
theme = darkTheme;
}
};

return (
<button className='general-menu-button' type="button" onClick={(e) => switchTheme(e)}>
<RiContrastLine />
</button>
);
};
export default DarkMode;

我试着添加useRef,但是由于我的理解有限,结果又是一个错误。

我想知道如何解决这个警告

为什么不在状态中存储主题呢?这将在呈现器之间保持值

在文件顶部导入useState:

import { useState } from 'react'

代替

let theme;

const [theme, setTheme] = useState(/* initial theme here */)

然后替换任何时候你分配主题给setTheme调用例如

theme = localStorage.getItem('theme')
// becomes
setTheme(localStorage.getItem('theme'))

最新更新