在我的Next.js应用程序中,我似乎无法访问窗口:

未处理的拒绝(ReferenceError):没有定义窗口

componentWillMount() {
    console.log('window.innerHeight', window.innerHeight);
}


当前回答

对于那些不能使用hook的人(例如,函数组件):

使用setTimeout(() => yourFunctionWithWindow());将允许它获得窗口实例。我想只是还需要一点时间来加载。

其他回答

“嗡�̶b̶r̶o̶w̶s̶e̶r̶ ̶t̶ ̶j̶u̶s̶t̶ ̶e̶x̶e̶c̶u̶t̶e̶ ̶y̶o̶u̶r̶ ̶c̶o̶m̶m̶a̶n̶d̶d̶u̶r̶n̶n̶ ̶r̶̶n̶n̶ ̶o̶n̶ ̶t̶ ̶c̶l̶i̶e̶n̶ ̶s̶i̶d̶e̶ ̶o̶n̶l̶y̶。

但是process object在Webpack5和NextJS中已经被弃用了,因为它是一个仅用于后端的NodeJS变量。

我们必须使用浏览器中的backwindow对象。

If (typeof window !== "undefined") { //客户端代码 }

其他解决方案是使用react钩子替换componentDidMount:

useEffect(() => { //客户端代码 })

没有SSR

https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

export default Home

对于这种情况,Next.js具有动态导入功能。

对于包含只在浏览器中工作的库的模块,建议使用动态导入。请参考

发生错误是因为窗口尚未可用,而组件仍在挂载。组件挂载后,可以访问窗口对象。

您可以创建一个非常有用的钩子来获取动态窗口。innerHeight或window.innerWidth

const useDeviceSize = () => {

  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)

  const handleWindowResize = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  }

  useEffect(() => {
    // component is mounted and window is available
    handleWindowResize();
    window.addEventListener('resize', handleWindowResize);
    // unsubscribe from the event on component unmount
    return () => window.removeEventListener('resize', handleWindowResize);
  }, []);

  return [width, height]

}

export default useDeviceSize 

用例:

const [width, height] = useDeviceSize();

对于Next.js 12.1.0版本,我发现我们可以使用process。标题,以确定我们是在浏览器中还是在节点端。希望能有所帮助!

export default function Projects(props) {
    console.log({ 'process?.title': process?.title });

    return (
        <div></div>
    );
}

1. 从终端,我接收{'进程?。标题':'节点'}

2. 从Chrome devtool,我建议{'进程?。Title: 'browser'}