在React中基于路由有条件地渲染组件

时间:2019-02-13 08:39:46

标签: reactjs

您好,我如何可以基于路由有条件地渲染我的组件?

我的app.js示例

changeset

在这种情况下,如果路由为 /登录

,我想隐藏侧边栏组件

2 个答案:

答案 0 :(得分:1)

您可以添加一个Switch,它不会为/login路由呈现任何内容,但会为其他所有路由呈现Sidebar

const App = () => (
  <Container fluid>
    <Row>
      <Col lg="2">
        <Switch>
          <Route path="/login" />
          <Route path="/" component={Sidebar} />
        </Switch>
      </Col>
      <Col lg="10">
        <main>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/login" component={Login} />
          </Switch>
        </main>
      </Col>
    </Row>
  </Container>
);

答案 1 :(得分:0)

因此,这里实际上有几种方法。我假设您正在使用react-router-dom提取Route组件,并且直接渲染App组件,例如ReactDOM.render(<App />, rootElement);

如果是这种情况,那么根据您的代码片段,最快的解决方案就是

const App = () => {
  const pathname = window.location.pathname
  return (
      <Container fluid>
        <Row>
          {pathname === '/login' ?
           <Col lg="2">
            <Sidebar />
          </Col> : null}
          <Col lg="10">
            <main>
              <Route exact path="/" component={Home} />
              <Route exact path="/login" component={Login} />
            </main>
          </Col>
        </Row>
    </Container>)      
}

如果使用App组件,例如<Route exact path="somePath" component={App} />

或者,在由withRouter提供的react-router-dom高阶组件包装后导出,并通过路由自动处理的historylocationmatch道具库,以便您进行以下更新

const App = ({location: {pathname}}) => {
  return (
      <Container fluid>
        <Row>
          {pathname === '/login' ?
           <Col lg="2">
            <Sidebar />
          </Col> : null}
          <Col lg="10">
            <main>
              <Route exact path="/" component={Home} />
              <Route exact path="/login" component={Login} />
            </main>
          </Col>
        </Row>
    </Container>)      
}

我假设,当前您的代码可以按预期的方式运行,而您唯一关心的是有条件地呈现SiderBar

但是,在设置多条路线时,我建议使用Switch https://reacttraining.com/react-router/web/api/Switch

提供的react-router-dom组件

此外,我可能不会以以下方式基于路径名动态显示/显示SideBar组件,而是按照以下方式创建诸如MainLayout的组件

const MainLayout = ({children}) => <div><SideBar/>{children}</div>

并更新我的Home组件,例如

const Home = () => <MainLayout>{content related to home page}</MainLayout>

因此,通过这种方式,SideBar仅在您希望其可见的页面中可见,而无需检查路径名

相关问题