简体   繁体   中英

Route doesn't work in react-router-dom in a nested structure

I want to build an anthentication page with routes:

/auth -> show auth status 
/auth/signin -> Sign in form 
/auth/signup -> Sign up form

Here are components in my App

App.js

function App() {
  return (
   <BrowserRouter>
   <div className="App">
   <Switch>
        <Route exact path="/auth" component={AuthPage} />
        <Route path="/notebook" component={SiderDemo} />
    </Switch>

   </div>
   </BrowserRouter>
  );
}

AuthPage.js

function AuthPage() {

    // get auth status 
    const auth  = seSelector(state => state.firebase.auth);
 
    let { path, url } = useRouteMatch(); 

    return (
        <Layout>
        <Layout.Header>
            <Link to={`${url}/signin`}>Sign in</Link>
            <Link to={`${url}/signup`}>Sign up</Link>
        </Layout.Header>
        <Layout.Content>
           <Switch>
               <Route path={`${path}/signin`}>
                <SigninForm />
                </Route>              
                <Route path={`${path}/signup`}>
                 <SignupForm />
                </Route>
                <Route exact path={path}>
                    <p>{isEmpty(auth) ? "Not logged in " : auth.uid}</p>
                </Route> 

           </Switch>

        </Layout.Content>
        <Layout.Footer>Footer</Layout.Footer>
      </Layout>
    )

}

Although the app renders /auth but when it goes to auth/signin and auth/signup it gets nothing. Can someone helps to fix it?

react-router-dom versions: ^5.2.0

Your second Switch render on top of AuthPage component. Because AuthPage render only if path is exactly auth , at auth/signin it won't rendered and therefore it childs routes not rendered as well. Remove exact from auth route declaration

<Route path="/auth" component={AuthPage} />

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