React Router 判断当前路由是否匹配 hook
通常需要根据请求地址设置某个导航或者按钮选中状态,react-router-dom
提供了 NavLink
组件,但是不够灵活,所以编写 useRouteMatch
hook 来实现手动控制,使用如下:
function Cmp(){
const isActive = useRouteMatch(链接地址);
// ....
}
源码:
/**
* 判断路由是否匹配
* @returns boolean
*/
export default function useRouteMatch(link: string | undefined) {
let location = useLocation();
let path = useResolvedPath(link || "");
let locationPathname = location.pathname;
let toPathname = path.pathname;
locationPathname = locationPathname.toLowerCase();
toPathname = toPathname.toLowerCase();
return (
locationPathname === toPathname ||
(locationPathname.startsWith(toPathname) &&
locationPathname.charAt(toPathname.length) === "/")
);
}