【问题标题】:localStorage is not defined - Next.jslocalStorage 未定义 - Next.js
【发布时间】:2021-03-18 05:55:48
【问题描述】:

我刚刚设置了一个函数来在使用 Tailwind CSS 时切换暗模式。这个错误突然出现,因为它像 5 分钟前一样工作正常。我没有更改任何代码,但突然出现此错误。

我正在使用 Next.js 和 Tailwind CSS。不是代码专家,只是学习和尝试。这是我使用 localStorage 的功能:

  const [theme, setTheme] = useState(localStorage.theme);
  const colorTheme = theme === 'dark' ? 'light' : 'dark';
  useEffect(() => {
    const root = window.document.documentElement;

    root.classList.remove(colorTheme);
    root.classList.add(theme);
    localStorage.setItem('theme', theme);
  }, [theme, colorTheme]);

  return [colorTheme, setTheme];
}

希望在这里有一些光线。这对我来说很奇怪,因为它正在工作????

【问题讨论】:

    标签: local-storage next.js tailwind-css


    【解决方案1】:

    这是因为 nextjs 在服务器端和客户端都运行。在服务器端,你不能访问拥有 localStorage 的 window 对象,它只会在组件挂载到 dom 时出现。因此,您可以像这样将 localStorage 移动到 useEffect 挂钩

    const [theme, setTheme] = useState();
    
    useEffect (() => {
      
         setTheme(localStorage.theme)
        
    }, []);
    

    【讨论】:

    • 从那时起,我从 useState 中删除了 localStorage.theme,将其默认设置为暗。但是现在 localStorage 根本不起作用。更改路由时,浏览器不记得打开了哪个主题,它会返回默认值。 export default function DarkModeToggle() { const [theme, setTheme] = useState('dark'); const colorTheme = theme === 'dark' ? 'light' : 'dark'; useEffect(() => { const root = window.document.documentElement;这个sn-p下面的代码保持不变。
    • 不要删除本地存储。只需将其移至 useEffect 挂钩即可。它应该工作。如果您创建一个最小的工作代码 sn-p 会很好。我会尽力帮助你
    • 不确定它是否正常工作,但我已尝试上传到沙箱:codesandbox.io/s/trusting-haslett-f31wk
    • 抱歉,我无法运行您的代码和框示例,存在终端错误
    猜你喜欢
    • 2021-10-17
    • 2022-10-31
    • 2018-02-14
    • 1970-01-01
    • 2016-12-29
    • 2022-01-06
    • 2021-10-06
    • 2020-03-20
    相关资源
    最近更新 更多