在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
当前回答
如果它是NextJS应用,并且在_document.js中,使用下面的方法:
<script dangerouslySetInnerHTML={{
__html: `
var innerHeight = window.innerHeight;
`
}} />
其他回答
如果它是NextJS应用,并且在_document.js中,使用下面的方法:
<script dangerouslySetInnerHTML={{
__html: `
var innerHeight = window.innerHeight;
`
}} />
没有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.js中开发web应用程序时,我也面临着同样的问题,这解决了我的问题,你必须在生命周期方法或react Hook中引用引用窗口对象。例如,假设我想用redux创建一个存储变量,在这个存储中我想使用一个windows对象,我可以这样做:
let store
useEffect(()=>{
store = createStore(rootReducers, window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__())
}, [])
....
所以基本上,当你使用window的对象时,总是使用钩子来玩或者componentDidMount()生命周期方法
日期:06/08/2021
检查窗口对象是否存在,然后跟随代码进行操作。
function getSelectedAddress() {
if (typeof window === 'undefined') return;
// Some other logic
}
在类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 = {}
}
}
这将避免错误(在我的例子中,错误将在我单击重载页面后发生)。