且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在React Router V4中实现嵌套路由(子路由)?

更新时间:2023-12-01 23:50:28

要创建嵌套路由,您需要删除exact:

To make nested routes you need to remove exact:

<Route path="/home" component={HomeRouter} />

并添加一些路线:

export const HomeRouter = ({match}) => {
 return(
   <div>
    <NavBar />
    {/* match.path should be equal to '/home' */}
    <Switch>
      <Route exact path={match.path} component={HomeView} />
      <Route exact path={match.path + '/contact'} component={HomeContact} />
    <Switch>
   </div>
 )

}

您不需要在嵌套路由中使用match.path,但是这样一来,如果您决定更改路由,则将所有内容从"/home"移动到"/new/home"将更加容易.

You don't need use match.path in nested routes but this way it will be easier to move everything from "/home" to "/new/home" in case you decide to change your routing.