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

Sha*_*oon 9 javascript reactjs react-router-dom

我有:

export const ACCOUNT_PORTAL_PATHS = [
      'home/*',
      'my-care/*',
      'chats/*',
      'profile/*',
      'programs/*',
      'completion/*',
    ]
Run Code Online (Sandbox Code Playgroud)

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

const { search: searchParams, pathname } = useLocation();
Run Code Online (Sandbox Code Playgroud)

在这个例子中,结果是:

pathname: "/my-care/1234"
Run Code Online (Sandbox Code Playgroud)

最好的搭配方式是什么?

提前致谢!

Dre*_*ese 1

如果您只想知道是否位于匹配的路径上,可以使用该matchPath函数并测试某些帐户路径前缀是否与当前的pathname.

例子:

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

...

const { pathname } = useLocation();
const isMatch = ACCOUNT_PORTAL_PATHS.some((path) =>
  matchPath(path, pathname)
);
Run Code Online (Sandbox Code Playgroud)

编辑史诗-shtern-gyuolz