简体   繁体   中英

React Router does not render new component on Route of child component

In App.js

 let routes = (
  <Switch>
    <Route path="/signin" component={SignIn} />
    <Redirect to="/signin" />
  </Switch>
)

// routes when user signed in
if (this.props.isAuthenticated) {
  routes = (
    <Switch>
      <Route path="/signout" component={SignOut} />
      <Route path="/" exact component={Dashboard} />
      <Redirect to="/" />
    </Switch>
  )
}
return (
  <div>
    {routes}
  </div>
);

Everything is working fine with those components and routes. But in the dashboard. I also want to have different routes. In this code below role always = admin to test

render() {
    let routes = null;
    switch (this.props.role) {
      case ('admin'):
        routes = (
          <Switch>
            <Route path='/uploads' component={UploadFileArea} />
          </Switch>
        );
        break;
      case ('student'):
        break;
      case ('lecturer'):
        break;
      default: routes = null;
    }
    return (
      <div>
        <NavigationBar username={this.props.username}/>
        <NavLink to='/uploads'>Uploads</NavLink>
        {routes}
      </div>
    );

I don't understand why the route to /uploads never works, it's always direct me to the dashboard which is '/'. Putting <Route path='/uploads' component={UploadFileArea} /> in App.js still works

It's because you have the exact flag on your / path. If you go to /uploads then your top level routes won't match anything and will Redirect back to / . If you remove the exact flag it will work except then it will also render when you're in /signout .

The simplest fix is to give your slash path a unique name like /dashboard , and redirect / to /dashboard . Then make sure inside your Dashboard component the path to your uploads route is /dashboard/uploads .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM