You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Material-UI Drawer ListItem 选中项高亮及路由跳转同步问题求助

解决方案:同步路由与Drawer菜单项的选中状态

你的问题核心在于当前的selectedIndex仅靠组件内部的useState维护——当通过Link跳转到新页面时,组件会重新渲染,状态会被重置,而且无法自动匹配当前的路由路径。要实现跳转后保持高亮,我们需要把路由信息和选中状态绑定起来。

步骤1:获取当前路由信息

首先导入React Router的useLocation钩子,它能帮我们拿到当前页面的路径:

import { useLocation } from 'react-router-dom';

步骤2:根据路由初始化并同步选中状态

修改你的状态逻辑,让selectedIndex根据当前路由自动设置,并且监听路由变化实时更新:

const location = useLocation();
// 初始化时根据当前路由设置选中索引
const [selectedIndex, setSelectedIndex] = React.useState(() => {
  switch(location.pathname) {
    case '/movies':
      return 1;
    case '/':
    default:
      return 0;
  }
});

// 监听路由变化,自动更新选中状态
React.useEffect(() => {
  switch(location.pathname) {
    case '/movies':
      setSelectedIndex(1);
      break;
    case '/':
    default:
      setSelectedIndex(0);
      break;
  }
}, [location.pathname]);

const handleListItemClick = (event, index) => {
  setSelectedIndex(index);
};

步骤3(可选):优化菜单项渲染(更易维护)

如果后续要添加更多菜单项,可以把菜单配置抽成数组,用map渲染,避免重复代码:

// 定义菜单配置
const menuItems = [
  { path: '/', label: 'Home', icon: <HomeIcon color="secondary" /> },
  { path: '/movies', label: 'Movies', icon: <MovieFilterIcon /> }
];

// 渲染菜单项
{menuItems.map((item, index) => (
  <Link key={index} to={item.path} style={{ textDecoration: 'none' }}>
    <ListItem 
      button 
      selected={selectedIndex === index} 
      onClick={(event) => handleListItemClick(event, index)}
    >
      <ListItemIcon>{item.icon}</ListItemIcon>
      <ListItemText primary={item.label} />
    </ListItem>
  </Link>
))}

为什么这个方案可行?

  • useLocation会实时返回当前的路由路径,不管是通过Link点击跳转,还是直接在地址栏输入URL刷新页面,我们都能拿到正确的路径。
  • 通过useEffect监听location.pathname的变化,路由切换时自动更新selectedIndex,保证菜单项的选中状态始终和当前路由匹配。

内容的提问来源于stack exchange,提问作者Ryan Fonseka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:42:44