reactjs react-router错误路径名,match不是函数

bf1o4zei  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(431)

我越来越
路径名. match不是函数
使用react-routermatchPath时出错。
下面是抛出异常的代码:

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

ckocjqey

ckocjqey1#

您正在使用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,
);

相关问题