如果当前路由与 React Router Dom v6 中的模式匹配,我该如何匹配?

How can I match if the current route matches a pattern in React Router Dom v6?

我有:

export const ACCOUNT_PORTAL_PATHS = [
      'home/*',
      'my-care/*',
      'chats/*',
      'profile/*',
      'programs/*',
      'completion/*',
    ]

如果当前路径是其中任何一个,我想知道。我设法通过以下方式获得当前路径:

const { search: searchParams, pathname } = useLocation();

这会产生,在这个例子中:

pathname: "/my-care/1234"

最好的搭配方式是什么?

提前致谢!

如果您只是想知道您是否在匹配路径上,您可以使用 matchPath 函数并测试 some 帐户路径前缀是否匹配当前 pathname.

示例:

import { matchPath } from "react-router-dom";

...

const { pathname } = useLocation();
const isMatch = ACCOUNT_PORTAL_PATHS.some((path) =>
  matchPath(path, pathname)
);