Javascript NextJS React 应用程序中未定义窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55151041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:15:49  来源:igfitidea点击:

Window is not defined in NextJS React app?

javascriptreactjsnext.js

提问by Leon Gaban

In my NextJSapp I can't seem to access window

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

Unhandled Rejection (ReferenceError): window is not defined

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

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

enter image description here

在此处输入图片说明

回答by Darryl RN

Other solution is by using process.browserto just execute your command during rendering in client side only.

其他解决方案是process.browser仅在客户端渲染期间使用仅执行您的命令。

if (process.browser) {
  // client-side-only code
}

回答by Alexander Staroselsky

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

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

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

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

在 NextJS 中,componentDidMount()仅在客户端window和其他浏览器特定 API 可用时执行。来自 NextJS维基

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.

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

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

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

回答by Kate

With No SSR

无SSR

https://github.com/zeit/next.js#with-no-ssr

https://github.com/zeit/next.js#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

回答by Rotareti

If you use React Hooksyou can move the code into the Effect Hook:

如果您使用React Hooks,您可以将代码移动到Effect Hook 中

import * as React from "react";

export const MyComp = () => {

  React.useEffect(() => {
    // window is accessible here.
    console.log("window.innerHeight", window.innerHeight);
  }, []);

  return (<div></div>)
}

The code inside useEffectis only executed on the client (in the browser), thus it has access to window.

里面的代码useEffect只在客户端(在浏览器中)执行,因此它可以访问window.

回答by RAVINDER MAHAJAN

componentWillMount()lifecycle hook works both on server as well as client side. In your case server would not know about windowor documentduring page serving, the suggestion is to move the code to either

componentWillMount()生命周期钩子适用于服务器和客户端。如果服务器不知道页面服务windowdocument在页面服务期间,建议将代码移动到

Solution 1:

解决方案1:

componentDidMount()

Or, Solution 2

或者,解决方案 2

In case it is something that you only want to perform in then you could write something like:

如果这是您只想执行的操作,那么您可以编写如下内容:

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

回答by RealScatman

In the constructor of your Class Component you can add

在类组件的构造函数中,您可以添加

    if (typeof window === 'undefined') {
        global.window = {}
    }

Example:

例子:

import React, { Component } from 'react'

import React, { Component } from 'react'

class MyClassName extends Component {

class MyClassName extends Component {

constructor(props){
    super(props)
    ...
    if (typeof window === 'undefined') {
        global.window = {}
    }

}

}

This will avoid the error (in my case the error would occur after I would click reload of the page)

这将避免错误(在我的情况下,在单击重新加载页面后会发生错误)