在react-router中模块化路由

时间:2015-12-23 11:36:46

标签: reactjs react-router

有没有办法使用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

3 个答案:

答案 0 :(得分:7)

一种解决方案是将它们包装在变量中:

0x002B

注意:您应该记得放入父路线的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"))

的渲染方法

答案 1 :(得分:0)

如果您想按需加载路由,则可以在使用Webpack时自动执行此操作。

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

总而言之,您需要使用可在需要时自动加载块的getter函数设置您的路线。

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);
      }
    }
  ]
};

答案 2 :(得分:0)

是的,你可以,但它有点hacky - 由于反应路由器v3的hacky性质。请参阅我在类似问题上的答案:

React-router import routes