2015-10-20 77 views
0

React-Router有一個嵌套的概念,使我很難想象應該在哪裏注入着陸頁。React-Router:在登陸頁面添加

例如:

<Route path="/" component={App}> 
     <Route path="login" component={Login} /> 
     <Route path="logout" component={Logout} /> 
     <Route path="about" component={About} /> 
     <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> 
</Route> 

在頂層組件的該實施例一部分與部件的其餘部分共享。

但是對於登錄頁面,可能沒有適合您的路線的父子關係。

Ergo,在使用react-router時如何管理登錄頁面?

+0

你可以使用'IndexRoute'來解決 – knowbody

+0

@knowbody但不IndexRoute有它背後的同一嵌套概念?着陸頁在應用程序的其餘部分之外擁有自己的結構。 –

回答

2

好吧,讓我在這裏回答。

如果我正確地理解了你,你可以做到的方式非常簡單直接。
我會做這樣的事情:

<Route path='/' component={LandingPage}> 
    <Route path='app' component={App}> 
    <Route path="login" component={Login} /> 
    <Route path="logout" component={Logout} /> 
    <Route path="about" component={About} /> 
    <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> 
    </Route> 
</Route> 

,然後只在您的App組件this.props.children

+0

但在整個項目中不會登陸頁面代碼呢?就像在每一層一些代碼保持不變,這個「this.props.children」是根據當前路線填充的? –

+0

我不認爲我理解你的問題......登陸頁面代碼是什麼? – knowbody

+0

它是一個獨立的組件,它不會共享與代碼其餘部分相同的結構。例如,我的應用程序的其餘部分都有一個標題,但着陸頁卻沒有。 –

0

React-Router中的IndexRoute允許您在到達應用程序的一部分時定義默認組件。因此,使用以下代碼,如果轉到「/」,頁面將呈現App組件,並將LandingPage組件注入其props.children。

<Route path="/" component={App}> 
    <IndexRoute component={LandingPage} /> 
    <Route path="login" component={Login} /> 
    <Route path="logout" component={Logout} /> 
    <Route path="about" component={About} /> 
    <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> 
</Route> 
2

我無法得到任何上述的答案工作,所以我決定只是做我的方式。這是我做的:

<Route path="/"> 
    <IndexRoute component={Landing}/> 
    <Route path="/" component={App}> 
    <Route path="login" component={LoginOrRegister} onEnter={redirectAuth}/> 
    <Route path="dashboard" component={Dashboard} onEnter={requireAuth}/> 
    <Route path="vote" component={Vote} onEnter={requireAuth}/> 
    <Route path="about" component={About}/> 
    </Route> 
</Route> 

主要組件包含着陸頁和應用程序本身都需要的最小值。在我的情況下,他們什麼也沒有分享,所以這個組件只是一個包裝div。

const Main = ({children}) => { 
    return (
     <div> 
      {children} 
     </div> 
    ); 
};