2015-07-18 102 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> 
);