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

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

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


当前回答

在刷新页面时,我也遇到了同样的问题(由于导入与SSR不能很好地工作)。

对我来说,固定它的是去发生这种情况的页面,并迫使导入是动态的:

import dynamic from 'next/dynamic';


const SomeComponent = dynamic(()=>{return import('../Components/SomeComponent')}, {ssr: false});

//import SomeComponent from '../Components/SomeComponent'

注释掉原始导入并动态导入组件将强制组件的客户端呈现。

动态导入在Nextjs的文档中有介绍: https://nextjs.org/docs/advanced-features/dynamic-import

我通过观看youtube视频找到了这个解决方案: https://www.youtube.com/watch?v=DA0ie1RPP6g

其他回答

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

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

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

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

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

发生错误是因为窗口尚未可用,而组件仍在挂载。组件挂载后,可以访问窗口对象。

您可以创建一个非常有用的钩子来获取动态窗口。innerHeight或window.innerWidth

const useDeviceSize = () => {

  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)

  const handleWindowResize = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  }

  useEffect(() => {
    // component is mounted and window is available
    handleWindowResize();
    window.addEventListener('resize', handleWindowResize);
    // unsubscribe from the event on component unmount
    return () => window.removeEventListener('resize', handleWindowResize);
  }, []);

  return [width, height]

}

export default useDeviceSize 

用例:

const [width, height] = useDeviceSize();

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

解决方案1:

componentDidMount()

或者,方案2

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

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

日期:06/08/2021

检查窗口对象是否存在,然后跟随代码进行操作。

 function getSelectedAddress() {
    if (typeof window === 'undefined') return;

    // Some other logic
 }

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

 import { useRouter } from "next/router";

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