[英]How to fix: Assignments to the 'theme' variable from inside React Hook useEffect will be lost after each render
I am a newbie in React, and I am working on a dark-mode function.我是 React 的新手,我正在研究暗模式功能。 It has a warning and I would like to ask what is the best way to fix it.
它有一个警告,我想问一下修复它的最佳方法是什么。 Thanks
谢谢
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;
I have tried to add useRef, but with my limited understanding, it turned out another error.我试图添加 useRef,但由于我的理解有限,结果又出现了另一个错误。
I would like to know how to resolve the warning我想知道如何解决警告
Why not store the theme in state?为什么不将主题存储在状态中? This will persist the value across rerenders
这将在重新渲染中保留值
Import useState at the top of your file:在文件顶部导入 useState:
import { useState } from 'react'
replace代替
let theme;
with和
const [theme, setTheme] = useState(/* initial theme here */)
then replace anytime you assign theme to a setTheme call eg然后在您将主题分配给 setTheme 调用时随时替换,例如
theme = localStorage.getItem('theme')
// becomes
setTheme(localStorage.getItem('theme'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.