当前位置 : 主页 > 网页制作 > React >

reactjs – 在react-router中模块化路由

来源:互联网 收集:自由互联 发布时间:2021-06-15
有没有办法用react-router来模块化你的路线,然后只需导入它们并组装它们? 所以不是这样的: Router Route path="/" component={App} Route path="inbox" component={Inbox} Route path="messages/" component={AllMessa
有没有办法用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>

我明白了:
警告:位置与任何路线都不匹配

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

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"))

注意:你应该记得放入父路由的render方法{this.props.children}

网友评论