如何组织React组件和容器进行路由

时间:2016-05-18 11:47:24

标签: reactjs react-router react-redux

我开始学习React(使用redux和react-router)并想知道如何组织我的应用程序(经典的“navabar with login / register control at top,sidebar with items and content area)。

我假设使用以下组件结构(容器?什么是正确的术语?):

App (it is container)
|=> NavBar
  |=>LoginRegisterContainer (if user not authentified)
    |=> Login (email, password, button "login", Link "or register")
    |=> Register (email, password, name, button "register, Link "or login")
    |=> PickAControl (Link "login", text "or", Link "register, each clicked reveals corresponding control and hides another one)
  |=> Profile menu (link to "my profile" and item "logout")
|=> Sidebar
  |=> Users (Link from "react-router" with "active" state)
  |=> Exams (Link from "react-router" with "active" state)
  ...
|=> UsersList
  |=> UserRow
  |=> UserRow
  ...
|=> ExamsList
  |=> ExamRow
  |=> ExamRow
  ...

现在,我希望用户react-router能够通过localhost:3000/loginlocalhost:3000/users的用户列表(一旦身份验证)在导航栏上显示“登录”控件。

据我所知,我应该像这样实现路由表:

render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>

      <Route path="/" component={NavBar}>
        <Route path="/" component={LoginRegisterContainer }>
          /* Section should be should only for unauthenticated users */
          <Route path="/" component={PickAControl }> /* 1. How to show it by default and hide once once of routes below navigated? */
          <Route path="/login" component={Login}>
          <Route path="/login" component={Register}>

          /* 2. how to show `Profile` control/container for authenticated users? */
        </Route>
      </Route>

      <Route path="/" component={Sidebar} />
      <Route path="/users" component={Users}/>
      <Route path="/exams" component={Exams}/>
    </Router>
  </Router>
), document.getElementById('app'))

我发现当通过状态在一个容器中实现时,如何显示/隐藏LoginRegister以及PickAControl等控件。但是如何通过路由器来做呢?

我完全不知道Profile控件的显示是否是路由器的责任?或者我应该以某种方式告诉NavBar用户已登录?

我几乎没有react-router实现它,但{this.props.children}的概念对我来说是不可理解的。即我知道如何在render函数中呈现控件/容器。但是如何用路由器实现呢?来自react-router-tutorial的样本没有澄清它,因为它只是非常简单且无意义的容器。

所以我的问题是如何正确实现所需的方案?或者如何修复我的架构以更加反应方式?

0 个答案:

没有答案