首页 > 解决方案 > 路由器不渲染孩子

问题描述

我正在尝试对我的路线实施身份验证检查。我的App组件是我的父路由,我想在App组件中呈现我的孩子。

问题:使用我当前的设置,路由器永远不会进入App组件并直接进入AuthRoutesif'/auth'匹配项

目标:如何确保如果'/auth'匹配,它首先进入App我渲染其子组件的组件?

索引.tsx

ReactDOM.render(
 <Provider store={store}>
    <ConnectedRouter history={history}>
        <Router />
    </ConnectedRouter>
 </Provider>,
 document.getElementById("root")
);

路由器.tsx

export default () => {
  return (
    <Switch>
      <Route path={'/'} component={App}>
        <Route path={'/auth'} component={AuthRoutes} />
        <Route component={AuthContainer}>
          <Route path={'/dashboard'} component={Dashboard} />
        </Route>
      </Route>
    </Switch>
  );
};

应用程序.tsx

const App: React.FC = ({ children }: Props<Component>) => {
  return (
    <Layout className="layout">
      <Nav theme={'light'} mode={'horizontal'} />
      <Content style={{ background: '#fff', padding: 24, margin: 0, minHeight: 280 }}>
        {children}
      </Content>
    </Layout>
  );
}
export default App;

标签: reactjsreact-router

解决方案


我在这里假设您使用的是最新版本的 react-router (v4),并且您似乎正在尝试按照以前版本的方式进行嵌套路由。

要将其应用于您的示例,您需要:

应用程序.tsx

const App: React.FC = ({ children }: Props<Component>) => {
  return (
    <Layout className="layout">
      <Nav theme={'light'} mode={'horizontal'} />
      <Content style={{ background: '#fff', padding: 24, margin: 0, minHeight: 280 }}>
        <Route path={'/auth'} component={AuthRoutes} />
        <Route component={AuthContainer}>
          <Route path={'/dashboard'} component={Dashboard} />
        </Route>
      </Content>
    </Layout>
  );
}
export default App;

路由器.tsx

export default () => {
  return (
    <Switch>
      <Route path={'/'} component={App} />
    </Switch>
  );
};

注意到区别了吗?嵌套路由 App组件内部,而不是它的子级。

您可以在此处参考迁移文档:https ://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/migrating.md#nesting-routes


推荐阅读