2015-12-23 225 views
5

有沒有一種方法與react-router模塊化你的路由,然後只需導入它們並組裝它們?模塊化路由反應路由器

因此,不是這樣的:

<Router> 
    <Route path="/" component={App}> 
     <Route path="inbox" component={Inbox}> 
     <Route path="messages/" component={AllMessages} /> 
     <Route path="messages/:id" component={Message} /> 
     </Route> 
     <Route path="calendar" component={Calendar}> 
     <Route path="year" component={Year}> 
      <Route path="month" component={Month}> 
      <Route path="week" component={Week}/> 
      </Route> 
     </Route> 
     </Route> 
    </Route> 
    </Router> 

你可以做這樣的事情:

let InboxRoutes = React.createClass({ 
    render: function(){ 
    return (
     <Route path="inbox" component={Inbox}> 
     <Route path="messages/" component={AllMessages} /> 
     <Route path="messages/:id" component={Message} /> 
     </Route> 
    ); 
    } 
}); 

<Router> 
    <Route path="/" component={App}> 
     <InboxRoutes/> 
     <CalendarRoutes/> 
    </Route> 
    </Router> 

我得到: Warning: Location did not match any routes

回答

6

一種解決辦法是將它們包裝在變量:

let InboxRoutes = (
    <Route path="inbox" component={Inbox}> 
     <Route path="messages/" component={AllMessages} /> 
     <Route path="messages/:id" component={Message} /> 
    </Route> 
) 

let CalendarRoutes = (/* define routes like above */) 

let routes = (
    <Router> 
     <Route path="/" component={App}> 
      {InboxRoutes} 
      {CalendarRoutes} 
     </Route> 
    </Router> 
) 

render(routes, document.getElementById("app")) 

注:你應該記得把父路線{this.props.children}

0

如果要按需加載你的路由的渲染方法,你可以,如果你使用的WebPack自動做到這一點。

以下是完整指南:Automatic Code Splitting for React Router

概括起來,你會設置你的路由了吸氣功能,在需要的時候會自動加載塊。

import App from 'containers/App'; 
 
function errorLoading(err) { 
 
    console.error('Dynamic page loading failed', err); 
 
} 
 
function loadRoute(cb) { 
 
    return (module) => cb(null, module.default); 
 
} 
 
export default { 
 
    component: App, 
 
    childRoutes: [ 
 
    { 
 
     path: '/', 
 
     getComponent(location, cb) { 
 
     System.import('pages/Home') 
 
      .then(loadRoute(cb)) 
 
      .catch(errorLoading); 
 
     } 
 
    }, 
 
    { 
 
     path: 'blog', 
 
     getComponent(location, cb) { 
 
     System.import('pages/Blog') 
 
      .then(loadRoute(cb)) 
 
      .catch(errorLoading); 
 
     } 
 
    } 
 
    ] 
 
};

0

是的,你可以,但它是一種哈克 - 由於反應路由器V3的哈克性質。請參閱我對類似問題的回答:

React-router import routes