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

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

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


当前回答

我必须从URL访问哈希,所以我想到了这个

const hash = global.window && window.location.hash;

其他回答

没有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

如果它是NextJS应用,并且在_document.js中,使用下面的方法:

<script dangerouslySetInnerHTML={{
        __html: `
            var innerHeight = window.innerHeight;
        `
        }} />

您可以尝试以下用例代码片段,例如获取当前路径名(CurrentUrl Path)

 import { useRouter } from "next/router";

 const navigator = useRouter()
 console.log(navigator.pathname);

当我在next.js中开发web应用程序时,我也面临着同样的问题,这解决了我的问题,你必须在生命周期方法或react Hook中引用引用窗口对象。例如,假设我想用redux创建一个存储变量,在这个存储中我想使用一个windows对象,我可以这样做:

let store
useEffect(()=>{
    store = createStore(rootReducers,   window.__REDUX_DEVTOOLS_EXTENSION__ && 
    window.__REDUX_DEVTOOLS_EXTENSION__())
 }, [])
 ....

所以基本上,当你使用window的对象时,总是使用钩子来玩或者componentDidMount()生命周期方法

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

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