【发布时间】:2021-11-18 06:47:53
【问题描述】:
我面临一个似乎无法解决的问题。
我有一个自定义钩子来设置窗口的高度和宽度。但是由于 nextjs 是 SSR 我得到了窗口未定义的错误。
我的问题在于将钩子放在 if 语句或 useeffect 钩子中。
当前代码(useWindowDimensions.tsx):
import { useState, useEffect } from 'react'
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window
return {
width,
height,
}
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions())
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions())
}
window.addEventListener('resize', handleResize)
// code here
return () => window.removeEventListener('resize', handleResize)
}, [])
return windowDimensions
}
当前代码:
const { height, width } = useWindowDimensions()
const dimensions = () => {
if (width > 1900) return width * 0.4
if (width > 1000) return width * 0.3
if (width > 800) return width * 0.2
if (width < 800) return width * 0.1
}
我不能将 getWindowDimensions() 放在 useEffect 中,因为钩子的规则
useEffect(() => {
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window
return {
width,
height,
}
}
})
【问题讨论】:
标签: reactjs react-hooks next.js