【问题标题】:Why is there a ReferenceError: window is not defined in Nextjs为什么会出现 ReferenceError: window is not defined in Nextjs
【发布时间】:2021-12-29 18:20:52
【问题描述】:

我正在尝试在 Nextjs 中使用带有 window 属性的 useState 钩子。但是,我收到了错误, ReferenceError: window is not defined。

目标:当屏幕尺寸发生变化时更新尺寸状态

实施:

import { useState } from 'react'

export const Dashboard = ({ children }) => {

  const [size, setSize] = useState(window.innerWidth) // <<< Error thrown here
  const updateSize = () => setSize(window.innerWidth)
  useEffect(() => (window.onresize = updateSize))
}

return {
  <div className=`{$toggleMenu || size >= 768 ? 'flex' : 'hidden'}`}>content</div>
}

我尝试将useState 放在条件和 useEffect 挂钩中,但这并不能解决问题。

【问题讨论】:

  • window 未在服务器端定义。因为你有 NextJS,我假设你正在做 ssr,这就是引发错误的地方。要解决它,只需在尝试访问 innerWidth 之前检查窗口对象是否存在,并在将侦听器添加到您的 useEffect 之前进行检查。
  • useState 不需要条件,只要在它上面定义一个新变量什么的。 const windowWidth = window?.innerWidth ?? 0; 然后做useState(windowWidth)

标签: reactjs next.js window use-state referenceerror


【解决方案1】:

我最近做了类似的事情并通过检查窗口对象是否存在来解决它,就像 Ian 评论的那样。

const breakpoints = (width) => {
    if(width < 640) {
      return 'xs';
    } else if(width >= 640 && width < 768 ) {
      return 'sm';
    } else if(width >= 768 && width < 1024) {
      return 'md';
    } else if(width >= 1024) {
      return 'lg';
    }
  };
  
  const [breakpoint, setBreakpoint] = useState(() => breakpoints(typeof window !== 'undefined' && (window.innerWidth)));

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const calcInnerWidth = function() {
        setBreakpoint(breakpoints(window.innerWidth))
      }
      window.addEventListener('resize', calcInnerWidth)
      return () => window.removeEventListener('resize', calcInnerWidth)
    }
  }, [])

有用的链接:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2018-10-28
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多