簡體   English   中英

如何修復:每次渲染后,React Hook useEffect 中對“主題”變量的賦值將丟失

[英]How to fix: Assignments to the 'theme' variable from inside React Hook useEffect will be lost after each render

我是 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'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM