繁体   English   中英

为什么会出现 ReferenceError: window is not defined in Nextjs

[英]Why is there a ReferenceError: window is not defined in Nextjs

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

目标:每当屏幕尺寸发生变化时,更新尺寸 state

实施

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 object 是否存在来解决它,就像 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)
    }
  }, [])

有用的链接:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM