简体   繁体   English

如何修复:每次渲染后,React Hook useEffect 中对“主题”变量的赋值将丢失

[英]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.

相关问题 每次渲染后,从 React Hook useEffect 内部对 'timeInterval' 变量的分配将丢失 - Assignments to the 'timeInterval' variable from inside React Hook useEffect will be lost after each render 来自 React Hook 内部的变量 useEffect 将在每次渲染后丢失 - Variable from inside React Hook useEffect will be lost after each render 为什么我收到此错误:React Hook useEffect 内部的变量在每次渲染后都会丢失? - Why i am getting this error: variable from inside React Hook useEffect will be lost after each render? 如何将子集合中的数据分配到其集合并呈现新对象? 使用 react、firebase 和 useeffect-hook - How to assign data from a subcollection to its collection and render the new object? Using react, firebase and useeffect-hook 修改 useEffect() 中使用 fetch() 调用的 React 挂钩变量 - Modify a React hook variable inside useEffect() that uses a fetch() call React Hook useEffect 缺少依赖项:&#39;notes&#39;,如何修复? - React Hook useEffect has a missing dependency: 'notes', how to fix it? useEffect 钩子完成后如何渲染组件? - How can I render the components after useEffect hook is finished? 如何解决此警告:“React Hook useEffect 缺少依赖项:'history'”? - How to fix this warning: “React Hook useEffect has a missing dependency: 'history'”? 使 React useEffect 钩子不在初始渲染上运行 - Make React useEffect hook not run on initial render React useEffect Hook 不会在具有 [] 依赖项的第一次渲染时触发 - React useEffect Hook not Triggering on First Render with [] Dependencies
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM