简体   繁体   English

路由在嵌套结构中的 react-router-dom 中不起作用

[英]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应用程序.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 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.虽然应用程序呈现/auth但当它进入auth/signinauth/signup时,它什么也得不到。 Can someone helps to fix it?有人可以帮忙解决吗?

react-router-dom versions: ^5.2.0 react-router-dom 版本:^5.2.0

Your second Switch render on top of AuthPage component.您的第二个Switch呈现在AuthPage组件之上。 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.因为AuthPage仅在 path 完全是auth时才会呈现,所以在auth/signin signin 不会呈现它,因此它的子路由也不会呈现。 Remove exact from auth route declarationauth路由声明中删除exact

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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