在NextJS React应用程序中未定义窗口吗? [英] Window is not defined in NextJS React app?

查看:298
本文介绍了在NextJS React应用程序中未定义窗口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 NextJS 应用中,我似乎无法访问window

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

Unhandled Rejection (ReferenceError): window is not defined

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

推荐答案

将代码从componentWillMount()移至componentDidMount():

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

在NextJS中,仅在window和其他特定于浏览器的API可用的客户端上执行componentDidMount().从NextJS Wiki :

In NextJS, componentDidMount() is executed only the client where window and other browser specific APIs will be available. From the NextJS wiki:

Next.js是通用的,这意味着它首先在服务器端执行代码, 然后是客户端.窗口对象仅存在于客户端,因此如果 您绝对需要在某些React组件中访问它,您 应该将该代码放在componentDidMount中.此生命周期方法将 仅在客户端上执行.您可能还需要检查是否 不是满足您需求的替代通用库.

Next.js is universal, which means it executes code first server-side, then client-side. The window object is only present client-side, so if you absolutely need to have access to it in some React component, you should put that code in componentDidMount. This lifecycle method will only be executed on the client. You may also want to check if there isn't some alternative universal library which may suit your needs.

同一行中,componentWillMount()在以下版本的v17中将已弃用 做出反应,因此在不久的将来有效地使用它可能是不安全的.

Along the same lines, componentWillMount() will be deprecated in v17 of React so it effectively will be potentially unsafe to use in the very near future.

这篇关于在NextJS React应用程序中未定义窗口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆