Next.js React 应用程序中未定义窗口 [英] Window is not defined in Next.js React app

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

问题描述

在我的

解决方案

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

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

在 Next.js 中,componentDidMount() 仅在客户端上执行,其中 window 和其他浏览器特定的 API 将可用.来自 下一步.js 维基:

<块引用>

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

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

In my Next.js app I can't seem to access window:

Unhandled Rejection (ReferenceError): window is not defined

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

解决方案

Move the code from componentWillMount() to componentDidMount():

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

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

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.

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.

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

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