Skip to content

Commit 8122965

Browse files
committed
fix: calculate active nav menu items with location.pathname
1 parent d08ecf5 commit 8122965

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

packages/theme-doc/src/Layout/Header.tsx

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React, { useContext, useMemo } from 'react'
22
import { Menu, Dropdown } from 'antd'
3-
import { Link, matchPath, PathPattern } from 'react-router-dom'
3+
import { Link, matchPath, PathPattern, useLocation } from 'react-router-dom'
44
import {
55
MenuUnfoldOutlined,
66
MenuFoldOutlined,
@@ -26,11 +26,16 @@ const AppHeader: React.FC<React.PropsWithChildren<Props>> = (props) => {
2626
const { render: renderLocaleSelector } = useLocaleSelector()
2727
const themeCtxValue = useThemeCtx()
2828
const {
29-
loadState: { routePath },
30-
resolvedLocale: { locale, localeKey },
29+
resolvedLocale: { locale },
3130
staticData,
3231
} = themeCtxValue
3332

33+
// use location.pathname instead of loadState.routePath
34+
// to calculate the active nav menu items
35+
// because loadState.routePath may have param placeholder like /users/[uid]
36+
// and it can't tell difference between /users/1 and /users/2
37+
const { pathname } = useLocation()
38+
3439
const renderLogo = (() => {
3540
const logoLink = (() => {
3641
let result: string | undefined | null
@@ -73,7 +78,7 @@ const AppHeader: React.FC<React.PropsWithChildren<Props>> = (props) => {
7378
const result = (resolvedTopNavs ?? [])
7479
.map(getActiveKeyIfMatch)
7580
.filter(Boolean)
76-
if (!result.includes(routePath)) result.push(routePath)
81+
if (!result.includes(pathname)) result.push(pathname)
7782
return result as string[]
7883

7984
function getActiveKeyIfMatch(item: MenuConfig) {
@@ -113,17 +118,15 @@ const AppHeader: React.FC<React.PropsWithChildren<Props>> = (props) => {
113118
} else {
114119
actualMatcher = matcher
115120
}
116-
// use loadState.routePath instead of location.pathname
117-
// because location.pathname may contain trailing slash
118-
return !!matchPath(actualMatcher, routePath)
121+
return !!matchPath(actualMatcher, pathname)
119122
} else {
120123
return matcher.some((oneMatcher) => {
121-
return !!matchPath(oneMatcher, routePath)
124+
return !!matchPath(oneMatcher, pathname)
122125
})
123126
}
124127
}
125128
}
126-
}, [routePath, resolvedTopNavs])
129+
}, [pathname, resolvedTopNavs])
127130

128131
return (
129132
<header className={s.header}>

0 commit comments

Comments
 (0)