如何在react新版本中获得匹配路径



我想要实现的是获得url的路径使用匹配,以显示商店类别。

我遇到的问题是,匹配是未定义的,即使我做console.log(match),它仍然显示未定义。

如果我应该单独console.log(match),那么页面将很好地显示组件,但匹配将从控制台未定义,但当我包括,因为它正在教程中使用,整个页面将变为空白,匹配仍将未定义。

有谁能帮帮我吗?我已经尽力了。

下面是shop.components.jsx


import React from "react";
import {BrowserRouter as Router, Route, Routes  } from 'react-router-dom';
import CollectionsOverview from "../../components/collections-overview/collections-overview.components";
const ShopPage = ({ match }) => {
console.log(match);
return(
<div className="shop-page">
<Route path={`${match.path}`} element={<CollectionsOverview/>} />
</div>
)};
export default ShopPage;

react-router-dom@6中不再有任何路由道具(即。history,location,match),所以match作为一个prop,是没有定义的。从我可以告诉你,你试图建立一个嵌套的路线类似于它是如何在RRDv5完成。RRDv6构建了相对于父Routes组件的嵌套路由和链接,因此没有必要尝试"构建"。对于这里的路由,你可以简单地使用path="/"作为路由,它将相对于Routes组件渲染ShopPage的路由。

的例子:

const ShopPage = () => {
return (
<div className="shop-page">
<Routes>
<Route path="/" element={<CollectionsOverview />} />
</Routes>
</div>
);
};

如果ShopPage组件在路径"/app/shopping/page"上渲染,那么CollectionsOverview也将在路径"/app/shopping/page"上渲染。

要在react新版本中获得匹配路径,您应该使用">useLocation";从反应

import React, { useLocation } from "react";
import {BrowserRouter as Router, Route, Routes  } from 'react-router-dom';
import CollectionsOverview from "../../components/collections-overview/collections-overview.components";
const ShopPage = () => {
const { pathname } = useLocation()
console.log(pathname);
// you can replace all path with "*" e.g path="*" which is commonly used for notfound page
return(
<div className="shop-page">
<Route path={`${match.path}`} element={<CollectionsOverview/>} />
</div>
)};
export default ShopPage;