开发者问题收集

react-router 错误 pathname.match 不是一个函数

2022-02-13
5312

当我使用 react-router matchPath 时,出现

pathname.match is not a function

错误。

这是引发异常的代码:

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>;
};

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

1个回答

您正在使用 react-router v6,新版本中 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;
}

这里 检查

您应该先传递 pattern ,然后传递 pathname :

const match = matchPath(
  { path: "/users/:id" },
  location.pathname,
);
Ghader Salehi
2022-02-13