2016-06-29 57 views
1

我有这样的路线:反应路由器使应用程序和登录

<Route path="/" component={App}> 
     <Route path="login"> 
      <IndexRoute component={LoginPage}/> 
     </Route> 
     <Route onEnter={requireAuth}> 
      <IndexRoute component={DashboardPage} /> 
      <Route path="accounts"> 
       <IndexRoute component={AccountPage}/> 
       <Route path="add" component={AccountAdd} /> 
       <Route path="detail/:id" component={AccountDetail} /> 
      </Route> 
      <Route path="contacts"> 
       <Route path="detail/:id" component={ContactPage}/> 
      </Route> 
      <Route path="transmissors"> 
       <Route path="detail/:id" component={TransmissorPage}/> 
      </Route> 
      <Route path="attends" component={AttendancePage} /> 
      <Route path="reports" component={ReportPage} /> 
      <Route path="configs" component={ConfigurationPage} /> 
     </Route> 
    </Route> 

在我的应用程序组件我想有一个条件来呈现登录页面和应用程序页面。

我不知道如何在我的应用程序有条件。

这里是我的应用程序代码:

class App extends React.Component{ 
    constructor(props) { 
     super(props); 
     console.log(this.props.children.type.name); 
    } 

    render() { 

     const loginRender = this.props.children.type.name == "LoginPage"; 
     const appRender = this.props.children.type.name != "LoginPage"; 

     return (


      {loginRender(
       <div className="app-container"> 
        {this.props.children} 
       </div> 
      )} 

      {appRender(
       <div className="app-container"> 
        <Header /> 
        <Sidebar /> 
        <Middle app={this.props.children}/> 
       </div> 
      )} 



     ); 
    } 
} 

export default App 

我不知道,如果使用this.props.children.type.name获得loginpage是最好的方法还是不错的实践。

回答

2

使用反应路由器,你需要的OnEnter方法检查用户是否在实际挂载应用程序组件之前进行了身份验证,如果未通过身份验证,则将用户重定向到“/ login”。您不需要在App组件内呈现LoginPage。例如:

//I use here token authentication, but it can be adopted easily in your case 
function redirect(nextState, replace) { 
    if (auth.loggedIn()) { 
    replace('app'); 
    } else { 
    replace('login'); 
    } 
} 

function redirectHome(nextState, replace) { 
    if (auth.loggedIn()) { 
    replace('app'); 
    } 
} 

function requireAuth(nextState, replace) { 
    if (!auth.loggedIn()) { 
    replace('login'); 
    } 
} 

<Router history={hashHistory}> 
    <Route path="login" component={Login} onEnter={redirectHome}/> 
    <Route path="app" component={Layout} onEnter={requireAuth}> 
     <IndexRoute component={Dashboard}/> 
     <Route path="accounts" component={Accounts}/> 
     <Route path="settings" component={Settings}/> 
    </Route> 
    <Route path="*" onEnter={redirect}/> 
</Router> 
在这个例子中登录页面的登录组件呈现

+0

我想在这里告诉你,如果我得到了 –

+0

我没有收到登录并进入应用页面,我可以编辑我的问题为你尝试帮我吗? –

+0

尝试在每个函数中使用console.log(auth.loggedIn())并查看它返回的内容。还尝试从函数 –

1

可以使用onEnter方法您的路线内与反应路由器

看看这个example

你可以看到太多的EnterHook