2015-07-18 115 views
1

我試圖爲分頁應用程序定義路由。使用反應路由器處理同一父級組件的子路由

/   -> handled by App 
/page/:page -> also handled by App 

這些是我的路線是這樣的:

var routes = (
    <Route name="app" path="/" handler={App}> 
     <Route name="paginated" path="page/:page" handler={App} /> 
    </Route> 
); 

這是應用程序的樣子:

var App = React.createClass({ 
    render : function() { 
     return (
      <div> 
       <RouteHandler/> 
       Something... 
      </div> 
     ); 
    } 
}); 

這裏的問題是,作爲paginatedapp的孩子路線,在組件Something...得到渲染兩次。

我在這裏想要實現的是默認爲app路由的頁面1,並加載paginated路由的所需頁面,而不加載兩次。

任何方式來做到這一點?

回答

0

使用App處理程序兩次按照您期望的方式工作 - 它稱爲App twice. However, the parent should only be used as the parent路由處理程序, and the children use their own處理程序。

獲取初始頁面正常加載,使用DefaultRoute的基本路徑:

路線

var routes = (
    <Route name="app" path="/" handler={App}> 
     <DefaultRoute handler={Home}/> 
     <Route name="paginated" path="page/:page" handler={Page} /> 
    </Route> 
); 

應用

var App = React.createClass({ 
    render : function() { 
     return (
      <div> 
       <RouteHandler/> 
      </div> 
     ); 
    } 
}); 

var Home = React.createClass({ 
    render : function() { 
     return (
      <div> 
       ...Something... 
      </div> 
     ); 
    } 
}); 

var Page = React.createClass({ 
    render : function() { 
     return (
      <div> 
       ...Something Completely Different... 
      </div> 
     ); 
    } 
}); 

的陣營路由器默認的處理程序文件有較大幅度的例子:

<Route path="/" handler={App}> 

    <!-- 
    When the url is `/`, this route will be active. In other 
    words, `Home` will be the `<RouteHandler/>` in `App`. 
    --> 
    <DefaultRoute handler={Home}/> 

    <Route name="about" handler={About}/> 
    <Route name="users" handler={Users}> 
    <Route name="user" handler={User} path="/user/:id"/> 

    <!-- when the url is `/users`, this will be active --> 
    <DefaultRoute name="users-index" handler={UsersIndex}/> 

    </Route> 
</Route> 

注意這裏<Route name="user" handler={User} path="/user/:id"/>也有一個默認路由,所以當沒有:id匹配它有某處去。

希望這會有所幫助!

+0

感謝您的回覆!這是我的第一個想法,但如果我需要在'paginated'中嵌套路線(實際上是這種情況),它不會真正起作用。 – ThisIsErico

-1

最後,我想出了一個使用重定向的解決方案,該解決方案允許我在paginated之一中擁有分頁和嵌套路由。

var routes = (
    <Route name="app" path="/" handler={App}> 
     <Redirect from="/" to="paginated" params={{ page : 1 }} /> 

     <Route name="paginated" path="page/:page" handler={PaginationLoader} /> 
    </Route> 
);