我得到
pathname.match不是函数
使用react-router
的matchPath时出错。
以下是引发异常的代码:
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>;
};
这是重现错误的最小沙盒示例。
您使用的是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,
);