react-router 错误 pathname.match 不是函数
react-router error pathname.match is not a function
我得到
pathname.match is not a function
当我使用 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>;
};
这是重现错误的最小示例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
你应该先通过 pattern
,然后是 pathname
:
const match = matchPath(
{ path: "/users/:id" },
location.pathname,
);
我得到
pathname.match is not a function
当我使用 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>;
};
这是重现错误的最小示例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
你应该先通过 pattern
,然后是 pathname
:
const match = matchPath(
{ path: "/users/:id" },
location.pathname,
);