如何在嵌套路径中进行 React Router Resolve

How to Make React Router Resolve within a nested path

我有点不确定这里可能出了什么问题。

我有一个 React 路由器交换机嵌套在另一个 React 路由器交换机中,如下所示

切换到homepage.js文件如下

<Switch>
       <Route path={HomePageRoutes.CONTENTS}> //which is just /contents
         <ContentPage initialData={fetchedData}/>
       <Route>
       <Route path={HomePageRoutes.ADS}>
         <AdsPage/>
       </Route>
</Switch>
         

现在,上面引用的 ContentPage 位于名为 contentpage.js 的文件中,该页面还包含如下开关:

export default function ContentPage(){
 ......
     <Switch>
        <Route path={`/first`}>
             <FirstContentPage/>
        </Route>
        <Route>
            <DefaultContentPage/>
        </Route>
     </Switch>
 ......
}                       

我原以为如果浏览器中的当前位置在 /content 并且我单击重定向到 /first 的 link,/first 将附加到当前位置成为 /content/first 并且 FirstContentPage 组件应该呈现但不幸的是它没有呈现?

我做错了什么?

期待您的参与。

您需要从 match 道具访问当前的 path。由于 ContentPage 没有收到 route props you may need to wrap ContentPage in the withRouter 高阶分量。

match

A match object contains information about how a <Route path> matched the URL. match objects contain the following properties:

  • params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
  • isExact - (boolean) true if the entire URL was matched (no trailing characters)
  • path - (string) The path pattern used to match. Useful for building nested <Route>s
  • url - (string) The matched portion of the URL. Useful for building nested <Link>s
function ContentPage({ match }) {
  const { path } = match;

  ......
    <Switch>
      <Route path={`${path}/first`}>
        <FirstContentPage/>
      </Route>
      <Route>
        <DefaultContentPage/>
      </Route>
    </Switch>
  ......
}

export default withRouter(ContentPage);