在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
当前回答
您可以定义一个状态变量并使用窗口事件句柄来处理这样的更改。
const [height, setHeight] = useState();
useEffect(() => {
if (!height) setHeight(window.innerHeight - 140);
window.addEventListener("resize", () => {
setHeight(window.innerHeight - 140);
});
}, []);
其他回答
有史以来最好的解决方案 从'next/dynamic'导入dynamic; const Chart = dynamic(()=> import('react-apexcharts'), { ssr:假的, })
如果你使用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>)
}
useEffect中的代码只在客户端(在浏览器中)执行,因此它可以访问window。
全球吗?。window && window. innerheight
使用运算符很重要。,否则构建命令可能会崩溃。
在类Component的构造函数中可以添加
if (typeof window === 'undefined') {
global.window = {}
}
例子:
import React, { Component } from 'react'
class MyClassName extends Component {
constructor(props){
super(props)
...
if (typeof window === 'undefined') {
global.window = {}
}
}
这将避免错误(在我的例子中,错误将在我单击重载页面后发生)。
您可以尝试以下用例代码片段,例如获取当前路径名(CurrentUrl Path)
import { useRouter } from "next/router";
const navigator = useRouter()
console.log(navigator.pathname);