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

React Router v6:如何让索引路由对应的NavLink处于激活状态?

解决索引路由下NavLink不激活的问题

问题核心:当处于/weather(索引路由)时,Weather组件中指向weather-forecast的NavLink,匹配路径是/weather/weather-forecast,与当前路径/weather不匹配,因此不会触发active状态。

方案一:重定向索引路由到子路由

修改App.tsx中的路由配置,将weather的索引路由改为重定向到weather-forecast,进入/weather时自动跳转到/weather/weather-forecast,NavLink就能正常匹配激活:

<Route path="weather" element={<Weather />}>
  {/* 替换原索引路由为重定向 */}
  <Route index element={<Navigate to="weather-forecast" />} />
  <Route path="weather-forecast" element={<WeatherForecast />} />
  <Route path="my-weather-stations" element={<WeatherStations />} />
</Route>

方案二:自定义NavLink的激活判断逻辑

如果希望保留索引路由的路径不变,给第一个NavLink添加isActive属性,手动判断当前路径是否为索引路由或目标子路由:

<NavLink 
  to="weather-forecast"
  // 路径为/weather或/weather/weather-forecast时标记为激活
  isActive={(match, location) => {
    return location.pathname === "/weather" || match !== null;
  }}
>
  Weather forecast
</NavLink>

两种方案均可解决问题,方案一逻辑更简洁,方案二保留了索引路由的原始路径行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:34:54