在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
当前回答
日期:06/08/2021
检查窗口对象是否存在,然后跟随代码进行操作。
function getSelectedAddress() {
if (typeof window === 'undefined') return;
// Some other logic
}
其他回答
在刷新页面时,我也遇到了同样的问题(由于导入与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
没有SSR
https://nextjs.org/docs/advanced-features/dynamic-import#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
有史以来最好的解决方案 从'next/dynamic'导入dynamic; const Chart = dynamic(()=> import('react-apexcharts'), { ssr:假的, })
日期:06/08/2021
检查窗口对象是否存在,然后跟随代码进行操作。
function getSelectedAddress() {
if (typeof window === 'undefined') return;
// Some other logic
}
componentWillMount()生命周期钩子在服务器端和客户端都可以工作。在您的情况下,服务器在页面服务期间不知道窗口或文档,建议将代码移动到任何一个
解决方案1:
componentDidMount()
或者,方案2
如果它是你只想执行的东西,那么你可以这样写:
componentWillMount() {
if (typeof window !== 'undefined') {
console.log('window.innerHeight', window.innerHeight);
}
}