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

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

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


当前回答

将代码从componentWillMount()移动到componentDidMount():

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

在Next.js中,componentDidMount()只在提供窗口和其他浏览器特定api的客户端上执行。来自Next.js wiki:

js是通用的,这意味着它首先在服务器端执行代码, 然后客户端。窗口对象只在客户端显示,因此if 你绝对需要在一些React组件中访问它 应该把该代码放在componentDidMount中。这个生命周期方法 只能在客户端执行。你可能还想检查一下是否有 是不是有其他的通用库可以满足你的需要。

同样,componentWillMount()将在React的v17中被弃用,因此在不久的将来使用它实际上可能是不安全的。

其他回答

将代码从componentWillMount()移动到componentDidMount():

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

在Next.js中,componentDidMount()只在提供窗口和其他浏览器特定api的客户端上执行。来自Next.js wiki:

js是通用的,这意味着它首先在服务器端执行代码, 然后客户端。窗口对象只在客户端显示,因此if 你绝对需要在一些React组件中访问它 应该把该代码放在componentDidMount中。这个生命周期方法 只能在客户端执行。你可能还想检查一下是否有 是不是有其他的通用库可以满足你的需要。

同样,componentWillMount()将在React的v17中被弃用,因此在不久的将来使用它实际上可能是不安全的。

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

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

对于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'}

componentWillMount()生命周期钩子在服务器端和客户端都可以工作。在您的情况下,服务器在页面服务期间不知道窗口或文档,建议将代码移动到任何一个

解决方案1:

componentDidMount()

或者,方案2

如果它是你只想执行的东西,那么你可以这样写:

componentWillMount() {
    if (typeof window !== 'undefined') {
        console.log('window.innerHeight', window.innerHeight);
    }
}

“嗡�̶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(() => { //客户端代码 })