【问题标题】:Theme Toggler not persisting through refresh despite localStorage use尽管使用了 localStorage,但主题切换器不会通过刷新持续存在
【发布时间】:2020-10-12 00:11:37
【问题描述】:

为一个项目做一个主题切换器,如果不刷新就可以完美运行。代码如下:

 const initialTheme = () => window.localStorage.getItem('theme') || true;
    const [lightTheme, setLightTheme] = useState(initialTheme);
    const { body } = document;

    useEffect(() => {
        window.localStorage.setItem('theme', lightTheme);

        lightTheme === true
            ? body.parentElement.dataset.theme = 'light'
            : body.parentElement.dataset.theme = 'dark'
    }, [lightTheme])

因此,当应用切换时,html 标记上的数据主题设置为浅色或深色。 但是,当我刷新时,无论如何页面都会回到深色主题。我的 html 标签上没有数据主题,我用上面的代码动态地做到了。

奇怪的是 localStorage 中的值总是正确的。当我将其设为浅色主题时,localStorage 值为真——它应该是——而当我将其设为深色主题时,该值为假(再次正确)。此 localStorage 值通过刷新保持不变。

如果可以的话请帮忙,谢谢!

【问题讨论】:

  • 在初始化lightTheme 时,您只是将函数传递给useState 中的函数体。您必须调用该函数才能评估值并像这样传递useState const [lightTheme, setLightTheme] = useState(initialTheme());

标签: javascript reactjs react-hooks local-storage themes


【解决方案1】:

当您从 localStorage 取回数据时,您将获得字符串值 "true" 或字符串值 "false"。因此,lightTheme 的值永远不会计算为true,并且您的代码始终呈现三元运算符的第二部分,即深色主题。尝试在 localStorage 中保留 'light''dark',并根据这些值进行切换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    相关资源
    最近更新 更多