在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
在我的Next.js应用程序中,我似乎无法访问窗口:
未处理的拒绝(ReferenceError):没有定义窗口
componentWillMount() {
console.log('window.innerHeight', 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();
其他回答
我必须从URL访问哈希,所以我想到了这个
const hash = global.window && window.location.hash;
对于那些不能使用hook的人(例如,函数组件):
使用setTimeout(() => yourFunctionWithWindow());将允许它获得窗口实例。我想只是还需要一点时间来加载。
您可以尝试以下用例代码片段,例如获取当前路径名(CurrentUrl Path)
import { useRouter } from "next/router";
const navigator = useRouter()
console.log(navigator.pathname);
日期:06/08/2021
检查窗口对象是否存在,然后跟随代码进行操作。
function getSelectedAddress() {
if (typeof window === 'undefined') return;
// Some other logic
}
当我在next.js中开发web应用程序时,我也面临着同样的问题,这解决了我的问题,你必须在生命周期方法或react Hook中引用引用窗口对象。例如,假设我想用redux创建一个存储变量,在这个存储中我想使用一个windows对象,我可以这样做:
let store
useEffect(()=>{
store = createStore(rootReducers, window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__())
}, [])
....
所以基本上,当你使用window的对象时,总是使用钩子来玩或者componentDidMount()生命周期方法