反应路由器 v6。matchPath 现在应该如何工作

Vad*_* P. 12 react-router react-router-dom

在版本 5 中,我可以通过这种方式执行检查https://v5.reactrouter.com/web/api/matchPath

import { matchPath } from "react-router";

const match = matchPath("/users/123", {
  path: "/users/:id",
  exact: true,
  strict: false
});
Run Code Online (Sandbox Code Playgroud)

在版本 6 中,我在屏幕上看到错误。现在应该如何运作? 错误:pathname.match 不是函数

Dre*_*ese 22

看起来react-router-dom@6传递的参数的顺序是颠倒的。

匹配路径

declare function matchPath<
  ParamKey extends string = string
>(
  pattern: PathPattern | string,
  pathname: string
): PathMatch<ParamKey> | null;

interface PathMatch<ParamKey extends string = string> {
  params: Params<ParamKey>;
  pathname: string;
  pattern: PathPattern;
}

interface PathPattern {
  path: string;
  caseSensitive?: boolean;
  end?: boolean;
}
Run Code Online (Sandbox Code Playgroud)

pattern是第一个参数,pathname是第二个参数。

pathname那么你已经通过了pattern

const match = matchPath("/users/123", {
  path: "/users/:id",
  exact: true,
  strict: false
});
Run Code Online (Sandbox Code Playgroud)

要解决交换传递给的参数顺序的问题matchPath

const match = matchPath(
  { path: "/users/:id" },
  "/users/123",
);
Run Code Online (Sandbox Code Playgroud)

  • [从 v5 升级](https://reactrouter.com/en/main/upgrading/v5#change-the-order-of-arguments-passed-to-matchpath-change-pathpattern-options) 文档中提到了这一点。但我同意这样的观点:从 v5 升级是相当痛苦且充满惊喜的! (3认同)