反应路由器错误pathname.match不是一个函数

Ahm*_*ınç 2 reactjs react-router react-router-dom

我越来越

pathname.match 不是函数

当我使用matchPath时出错react-router。

这是抛出异常的代码:

import { matchPath, useLocation } from "react-router";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";

const MatcherControl = () => {
  const location = useLocation();
  const match = matchPath(location.pathname, {
    path: "/users/:id",
    exact: true,
    strict: false
  });
  return <div>{match ? "matches" : "not matches"}</div>;
};
Run Code Online (Sandbox Code Playgroud)

这是重现错误的最小示例沙箱。

小智 8

您使用的是react-routerv6,新版本中参数的顺序matchPath颠倒了:

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:

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

  • 没有什么比一个没有任何改变的重大 API 更改更好的了 (2认同)