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

问题描述 投票:0回答:2

我正在尝试在 Nextjs 中使用带有

useState
属性的
window
钩子。但是,我收到错误信息,
 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 挂钩中,但这并不能解决问题。

reactjs next.js window use-state referenceerror
2个回答
2
投票

我最近做了类似的事情并通过检查 window 对象是否存在来解决它,就像 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)
    }
  }, [])

有用的链接:


0
投票

你可以使用antd design useBreakpoint https://ant.design/components/grid

© www.soinside.com 2019 - 2024. All rights reserved.