简体   繁体   中英

Default routing in react-router-dom not working, when using conditional rendering

I have the following React component:

function Routes(props) {
  const { role, userId } = props;

  const renderMemberTasksPage = (props) => {
    //Redirects to 404 or not
  };

  const renderTracksPage = (props) => {
     //Redirects to 404 or not
  };

  return (
    <>
      <Switch>
        <Route exact path='/members/:id/tasks' render={renderMemberTasksPage} />
        <Route exact path='/members/:id/tasks/id:open?' render={renderMemberTasksPage} />

        {role === 'admin' && (
          <Route path='/members/new'>
            <NewMember />
          </Route>
        )}

        {(role === 'admin' || role === 'mentor') && (
          <>
            <Route exact path='/'>
              <Redirect to='/members' />
            </Route>
            <Route exact path='/members'>
              <MembersManagerPage />
            </Route>
            <Route exact path='/tasks/'>
              <MemberTasksPage />
            </Route>
            <Route path='/tasks/new'>
              <NewTask />
            </Route>
            <Route exact path='/tasks/id:open?'>
              <MemberTasksPage />
            </Route>
            <Route path='/tasks/id:open/edit'>
              <MemberTasksPage edit />
            </Route>
            <Route path='/members/:id/progress'>
              <MemberProgressPage />
            </Route>
          </>
        )}

        {role === 'member' && (
          <>
            <Route exact path='/'>
              <Redirect to={`/members/${userId}/tasks`} />
            </Route>
            <Route path='/members/:id/tracks' render={renderTracksPage} />
          </>
        )}

        <Route exact path='/404'>
          <Error404Page />
        </Route>

        <Route path='*'>
          <Redirect to='/404' />
        </Route>

      </Switch>
    </>
  );
}

In simple words, this code defines routes depending on the current user role. Here I've got a problem: default router * is not working. Different order of routes and using exact in different combinations showed no results. When I removed all routes, rendered conditionally, it worked. Can it be the reason and how to avoid such behavior?

My version of react-router-dom:

 "react-router-dom": "^5.1.2"

I think you can remove the path='*' and put directly the component inside the <Route>

It would be something like that:

   <Route>
      <Error404Page />
   </Route>

since the Switch will try to match every path the last one will be used if it can't find any

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