我得到了
pathname.match is not a function
使用 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>;
};
这是最小的例子 sandbox重现错误。
最佳答案
您正在使用 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;
}
查一下here
您应该先传递模式
,然后传递路径名
:
const match = matchPath(
{ path: "/users/:id" },
location.pathname,
);
关于reactjs - react-router 错误 pathname.match 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71100360/