React-Router V6 检查路径是否与模式匹配

gho*_*hri 13 reactjs react-router

我正在尝试在react-router v6中检查“/admin/posts/new”到“/admin/*”。我发现有一个matchRoutes函数

import { useLocation } from "react-router";
const { pathname } = useLocation();
const isAdminPath = someMatchFunc(pathname,"/admin/*") <<<< something goes here returns true or null
Run Code Online (Sandbox Code Playgroud)

amr*_*nea 16

您应该能够使用 matchPath 函数。在 v6 中它看起来像这样:

import { useLocation, matchPath } from "react-router";
const { pathname } = useLocation();
const isAdminPath = matchPath("/admin/*", pathname);
Run Code Online (Sandbox Code Playgroud)

值得注意的是,他们更改了 v6 中的参数。在 v5 中,您可能会这样做。

import { useLocation, matchPath } from "react-router";
const { pathname } = useLocation();
const isAdminPath = matchPath(pathname, { path: "/admin", exact: false });
Run Code Online (Sandbox Code Playgroud)

  • 但 matchPath 不考虑基本名称。我们需要添加什么才能匹配路径和基本名称。 (3认同)

小智 -1

改用useRouteMatchmatchPath

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

function BlogPost() {
  let match = useRouteMatch("/blog/:slug");

  // Do whatever you want with the match...
  return <div />;
}
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于 React Router v5,因为 v6 中未导出 `useRouteMatch`。 (2认同)