How to implement nested Routing (child routes) in

2019-09-19 13:12发布

问题:

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.