2016-04-19 109 views
1

看看react-router github上的huge-apps示例,我不知道如何设置我想要的路由。React路由器与嵌套的孩子?

URL  | Result 
-------------------------- 
/sites  | List of sites 
/sites/:id | One site 

如果我想列出多个站点,站点组件/路由将需要嵌套在站点组件/路由中。因此,我的文件夹结构看起来与react-router示例中的Assignments模型类似。

/routes 
    /Sites 
     /components 
     | Sites.js 
     /routes 
     | /Site 
     | | /components 
     | | | Site.js 
     | | index.js 
     index.js 

但是,对于/sites/:id路由,它不依赖于站点组件。我会在“网站”目录的同一级别创建另一个“网站”目录吗?还是让“网站”组件能够呈现列表和单一视图?我的index.js文件会是什么样子?

回答

3

我会想象你的路由树是这样的:

/sites 
(Sites.js) 
- /:id1 
    (Site1.js) 
- /:id2 
    (Site2.js) 

您index.js里面,这样的事情(使用客户端为例):

render((
    <Router history={browserHistory}> 
    <Route path="/" component={App}> 
     <IndexRoute component={Home} /> 
     <Route path="/sites" component={Sites}> 
     <Route path="/sites/:id" component={Site}/> 
     </Route> 
    </Route> 
    </Router> 
), document.getElementById('app')); 

每条路都有附随零件。你可以在这些组件中抛出任何你想要的东西,尽管包含一些导航到子路由的方式可能会有所帮助。

PlainRoute版本(虽然我不知道你为什么会想):

const rootRoute = { 
    component: 'div', 
    childRoutes: [{ 
    path: '/', 
    component: require('./components/App'), 
    childRoutes: [ require('./routes/Sites') ] 
    }] 
} 

render(
    <Router history={browserHistory} routes={rootRoute} />, 
    document.getElementById('example') 
); 

'./routes/Sites ':

module.exports = { 
    path: 'sites', 
    getChildRoutes(location, cb) { 
    require.ensure([], (require) => cb(null, [ require('./routes/Site') ])) 
    }, 
    getComponent(nextState, cb) { 
    require.ensure([], (require) => cb(null, require('./components/Sites'))) 
    } 
} 

' ./routes/Site' :

module.exports = { 
    path: 'sites/:id', 
    getComponent(nextState, cb) { 
    require.ensure([], (require) => cb(null, require('./components/Site'))) 
    } 
} 
+0

您如何对PlainRoutes进行此操作,示例如何? – GreeKatrina

+0

在可读性方面,当JSX更高效时,我不知道为什么要使用PlainRoutes。根据示例中使用的文件结构,我将在PlainRoutes版本中追加到最初的答案。 –

+0

正如你可以看到[这里](https://github.com/reactjs/react-router/blob/master/examples/huge-apps/app.js),它更适合代码分割。无论如何,先谢谢你。 – GreeKatrina

1

如果我理解你想达到什么样正确的,你可以做你的路由器里是这样的:

<Route path="/sites/:id" component={SingleSite} /> 
<Route path="/sites" component={Sites} /> 

SingleSite组件占用的ID PARAM,并用它来显示网站。如果有ID,React路由器应该能够使用SingleSite组件,如果没有,则显示Sites组件。

+0

当您映射/创建每个站点时,您是否可以通过站点组件将一个道具传递给站点组件? – GreeKatrina

+0

我想这取决于您是否希望“Site”组件显示为“Sites”组件的子项或不显示。我认为,因为你不想同时显示列表和个人网站,最好让他们的兄弟姐妹在与所有网站都有对象的父母身上。 'Sites'将遍历该对象并显示所有内容,'Site'将在react路由器的params道具中接收':id',然后过滤从父路由传递的道具。 –

+0

这是有道理的。我猜想在一个组件中使它更像MVC中的模型而不是组件。是否有必要先把更深的路径?例如,将'/ sites /:id'放在'/ sites'路由之后会导致'/ sites /:id'永远不会被渲染? – GreeKatrina