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

标签 reactjs react-router react-router-dom

我得到了

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/

相关文章:

javascript - Reactjs Ref 在另一个组件中

javascript - 如何修复 ReactJS 中的 "too much recursion"错误?

javascript - 如何根据 API 中的数据在两个 ui 容器之间进行选择 [React TypeScript]

reactjs - React Flux 架构有什么好的 Http 库吗

node.js - 使用 Express 设置 React Router

javascript - 动态路径 NavLink React

javascript - typescript JSDoc ...休息类型语法

reactjs - React 路由将子路由移动到单独的模块?

reactjs - 如何根据当前 url 使 antd 侧边栏菜单项处于事件状态?

javascript - 使用重定向时 react 父组件完全重建