react-router-dom V5 中的嵌套路由不起作用

Nested Routing in react-router-dom V5 not working

我正在尝试使用 react-router-dom v5 对我的 React 应用程序进行嵌套路由,但我卡住了!

这是我的商店组件代码:

import React from "react";
import CollectionsOverview from "../../components/collections-overview/collections-overview.component";
import CollectionPage from "../collection/collection.component";
import {  Link, Route } from "react-router-dom";


const  ShopPage = ({ match }) => {
    console.log(match.path);
    return(
    <div className="shop-page">
        <Link to='/shop/hats'>to Hats</Link>
        <Route exact path={`${match.path}`} component={CollectionsOverview}/>
        <Route path={`${match.path}/hats`} component={CollectionPage}/>
    </div>
);
};




export default ShopPage;

商店组件由 App.js 中的路由渲染 这是代码

<Switch>
      <Route  exact path='/' component={HomePage} />
      <Route  exact path='/shop' component={ShopPage} />
      <Route  exact path='/checkout' component={CheckoutPage} />
      <Route  
        exact path='/signin' 
        render={() => 
          this.props.currentUser  ? (
            <Redirect to='/' />
          ) : (
            <SignInAndSignUpPage/>
          )
        } 
      />
    </Switch>

并且我试图在路径中使用 match.path 而不是 '/shop/hats' 但是当我在浏览器中转到 /shop/hats 时它不会呈现任何内容。 奇怪的是,包含 CollectionsOverview 组件的第一个 Route 工作正常,但第二个不是。 你们能帮我吗?

编辑:我制作了一个 codesandbox 项目,其文件结构与我原来的项目相同,并设法重现了同样的问题。 the codesandbox link

渲染嵌套路由时,您需要允许您的 root/lower-level Route 组件也匹配它们可能正在渲染的任何 sub-routes/paths。这里的问题是您 exactly 匹配 App 中的路线,因此例如当您从 Shop 导航到 "/shop/hats" 时,"/shop" 路径不再准确匹配并且 Shop 被卸载,因此卸载它可能正在渲染的任何嵌套路由。

<Switch>
  <Route exact path="/" component={HomePage} />
  <Route exact path="/shop" component={ShopPage} />
</Switch>

RRDv5 中的路由路径更像是“path-prefixes”。没有允许任何 "/shop/*" path when using the exact` 道具的路线。

Switch 组件路径顺序和特异性很重要。如果命令正确,几乎根本不需要使用 exact 道具。在 Switch 中,您应该按特异性降序排列路径,并删除 exact 道具。这是通过允许 Switch 在回退到 less 特定路径之前先匹配 more 特定路径来实现的。

<Switch>
  <Route path="/shop" component={ShopPage} />
  <Route path="/" component={HomePage} />
</Switch>