React开发中点击浏览器前进后退切换页面时如何更新子菜单状态
解决办法
你需要监听路由变化事件来同步子菜单的打开状态,根据你使用的技术栈,有两种常用实现方式:
使用React Router的场景(v5/v6通用)
直接通过useLocation钩子拿到当前路径,用useEffect监听路径变化,匹配对应菜单项的id更新state即可:
import { useEffect, useState } from 'react'; import { useLocation } from 'react-router-dom'; // 保留你原有的逻辑 const [open, setOpen] = useState(); const toggle = (id) => setOpen(id); // 新增路由监听同步逻辑 const location = useLocation(); useEffect(() => { // 此处替换为你自己的路由和菜单id匹配逻辑 const matchNavId = yourMenuConfig.find(menu => menu.path === location.pathname)?.navId; setOpen(matchNavId); // 如果不需要自动打开对应子菜单,仅需要关闭所有已打开的菜单,直接写setOpen(undefined)即可 }, [location.pathname]);
未使用路由库的场景
直接监听浏览器原生的popstate事件,该事件会在用户点击前进/后退按钮时触发:
import { useEffect, useState } from 'react'; const [open, setOpen] = useState(); const toggle = (id) => setOpen(id); useEffect(() => { const handleHistoryChange = () => { const currentPath = window.location.pathname; // 替换为你自己的匹配逻辑 const matchNavId = yourMenuConfig.find(menu => menu.path === currentPath)?.navId; setOpen(matchNavId); }; window.addEventListener('popstate', handleHistoryChange); return () => window.removeEventListener('popstate', handleHistoryChange); }, []);
内容的提问来源于stack exchange,提问作者BraulioPortela
相关产品推荐
相关产品推荐

