How to implement nested Routing (child routes) in react router v4?

只谈情不闲聊 提交于 2019-12-13 08:03:35

问题


The component tree i want is as below - Login - Home - Contact - About

Contact and About are children of Home. This is my App.js ,

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>

          <Route exact path="/home" component={HomeView} />

        </div>
      </BrowserRouter>
    );
  }
}

render(<App />, document.getElementById('root'));

This is Home,

export const HomeView = ({match}) => {
 return(
   <div>
    <NavBar />


    Here i want to render the contact component, (Navbar need to stay)

   </div>
 )

}

This is my Navbar,

 export const NavBar = () => {
  return (
    <div>
      <Link to="/home">Home</Link> 
      <Link to="/home/contact">Contact</Link> 

      <hr/>
    </div>
  )
}

Contact component just need to render "hello text".


回答1:


To make nested routes you need to remove exact:

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

And add some routes:

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>
 )

}

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.



来源:https://stackoverflow.com/questions/55238776/how-to-implement-nested-routing-child-routes-in-react-router-v4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!