大佬教程收集整理的这篇文章主要介绍了React Hooks + Media Query 页面刷新问题,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个响应式侧边栏,逻辑实现如下,当屏幕低于 765 像素时侧边栏会自动隐藏,但问题是当我刷新低于 765 像素的页面时侧边栏会显示出来像这样
我的代码是这样的
function SIDebar(props) {
const {somevalue} = useContext(SIDebarContext);
const {SIDebarValue,SIDebarWallpapervalue} = React.useContext(CounterContext);
const [SIDebarthemeValue] = SIDebarValue;
const [SIDebarBACkgroundValue] = SIDebarWallpaperValue;
const [sIDebarOpen,setSIDebarOpen] = useState(true);
const [SIDebarbuttonContainer,setSIDebarbuttonContainer] = useState(false);
useEffect(() => {
window.addEventListener("resize",resizE);
})
const resize = () => {
if(window.innerWIDth < 765) {
setSIDebarOpen(false)
setSIDebarbuttonContainer(true)
} else {
setSIDebarOpen(true)
setSIDebarbuttonContainer(false)
}
}
const showSIDebar = () => {
setSIDebarOpen(!sIDebarOpen)
}
return (
<>
{
SIDebarbuttonContainer ? <div classname={"showSIDebarbuttonContainer"}>
<img classname={"showSIDebarbutton"} onClick={() => showSIDebar()} src={SIDebarMenuIcon} alt={"Open"} />
</div> : null
}
<Menu isOpen={sIDebarOpen}>
</Menu>
</>
);
}
我假设当我刷新页面时 sIDebarOpen
值变为真,尽管我在 resize 方法中进行了检查并注意到当我开始缩小屏幕时侧边栏消失了,它看起来像这样
侧边栏的默认状态是打开的,但是您必须根据宽度计算初始状态。此外,您必须仅在初始渲染时调整窗口大小时初始化侦听器。
const [sideBarOpen,setSideBarOpen] = useState(() => window.innerWidth > 765);
const [SideBarButtonContainer,setSideBarButtonContainer] = useState(() => window.innerWidth < 765);
useEffect(() => {
window.addEventListener("resize",resizE);
},[]); // Only initialize listener on initial render
const resize = () => {
if(window.innerWidth < 765) {
setSideBarOpen(false)
setSideBarButtonContainer(true)
} else {
setSideBarOpen(true)
setSideBarButtonContainer(false)
}
}
,
在实际渲染到屏幕之前尝试使用 useLayoutEffect
推送一些状态更改。
useLayoutEffect(() => {
if (window.innerWidth < 765) {
setSideBarOpen(false);
setSideBarButtonContainer(true);
}
window.addEventListener("resize",[])
以上是大佬教程为你收集整理的React Hooks + Media Query 页面刷新问题全部内容,希望文章能够帮你解决React Hooks + Media Query 页面刷新问题所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。