Nested Routes not rendering with React Router v4

醉酒当歌 提交于 2019-11-26 12:31:57

问题


I am trying to group some of my routes together with React Router v4 to clean up some of my components. For now I just want to have my non logged in routes group together and my admin routes grouped together but the following doens\'t work.

main.js

const Main = () => {
  return (
    <main>
      <Switch>
        <Route exact path=\'/\' component={Public} />
        <Route path=\'/admin\' component={Admin} />
      </Switch>
    </main>
  );
};

export default Main;

public.js

const Public = () => {
  return (
    <Switch>
      <Route exact path=\'/\' component={Greeting} />
      <Route path=\'/signup\' component={SignupPage} />
      <Route path=\'/login\' component={LoginPage} />
    </Switch>
  );
};

export default Public;

The Greeting component shows at \"localhost:3000/\", but the SignupPage component does not show at \"localhost:3000/signup\" and the Login component doesn\'t show at \"localhost:3000/signup\". Looking at the React Dev Tools these two routes return Null.


回答1:


The reason is very obvious. for your route in main.js, you have specified the Route path of Public component with exact exact path='/' and then in the Public component you are matching for the other Routes. So if the route path is /signup, at first the path is not exact so Public component is not rendered and hence no subRoutes will.

Change your route configuration to the following

main.js

const Main = () => {
  return (
    <main>
      <Switch>
        <Route path='/' component={Public} />
        <Route path='/admin' component={Admin} />
      </Switch>
    </main>
  );
};

export default Main

public.js

const Public = () => {
  return (
    <Switch>
      <Route exact path='/' component={Greeting} />
      <Route path='/signup' component={SignupPage} />
      <Route path='/login' component={LoginPage} />
    </Switch>
  );
};

Also when you are specifying the nested routes these should be relative to the parent Route, for instance if the parent route is /home and then in the child Route you wish to write /dashboard . It should be written like

<Route path="/home/dashboard" component={Dashboard}

or even better

<Route path={`${this.props.match.path}/dashboard`} component={Dashboard}


来源:https://stackoverflow.com/questions/45626214/nested-routes-not-rendering-with-react-router-v4

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