在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
当前回答
全球吗?。window && window. innerheight
使用运算符很重要。,否则构建命令可能会崩溃。
其他回答
发生错误是因为窗口尚未可用,而组件仍在挂载。组件挂载后,可以访问窗口对象。
您可以创建一个非常有用的钩子来获取动态窗口。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();
您可以尝试以下用例代码片段,例如获取当前路径名(CurrentUrl Path)
import { useRouter } from "next/router";
const navigator = useRouter()
console.log(navigator.pathname);
有史以来最好的解决方案 从'next/dynamic'导入dynamic; const Chart = dynamic(()=> import('react-apexcharts'), { ssr:假的, })
在刷新页面时,我也遇到了同样的问题(由于导入与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
对于Next.js 12.1.0版本,我发现我们可以使用process。标题,以确定我们是在浏览器中还是在节点端。希望能有所帮助!
export default function Projects(props) {
console.log({ 'process?.title': process?.title });
return (
<div></div>
);
}
1. 从终端,我接收{'进程?。标题':'节点'}
2. 从Chrome devtool,我建议{'进程?。Title: 'browser'}