如何在反应路由器中将子路由定义为反应组件

How to define child routes as react components in react-router?

本文关键字:路由 定义 组件 路由器      更新时间:2023-09-26

我有main.js

import { render } from 'react-dom';
import { browserHistory, Router, Route, IndexRoute } from 'react-router';
import Home from './containers/Home';
import ApplicationsRoutes from './applications/routes';
render((
  <Router history={browserHistory}>
    <Route path="/" component="div">
      <IndexRoute component={Home} />      
      <ApplicationsRoutes />
    </Route>
  </Router>
), document.getElementById('app'));

/application/routes.js

import { browserHistory, Router, Route, IndexRoute } from 'react-router'
import ApplicationsHome from './containers/ApplicationsHome';
export default () => (
  <Route path="applications" component={ApplicationsHome} />
);

我期望来自/application/routes.js的路由将被添加到主路由器中,因此应用程序主页将被渲染为路径/applications

不幸的是,事实并非如此。我收到错误:

Location "/applications" did not match any routes

对我来说,看起来这种组成路由器的方式不起作用,但我不明白这样做的正确方法是什么。

通常,当您执行此操作时,您应该考虑使用 PlainRoute 语法而不是 JSX 语法,然后在父路由上使用 getChildRoutes 来解析子路由,根据 huge-apps 示例: https://github.com/rackt/react-router/tree/master/examples/huge-apps

然后,这将使您能够轻松配置代码拆分和动态路由。

对于单数路由,您可以将路由导出为 JSX 元素:

export default <Route path="applications" component={ApplicationsHome} />;

并像这样包含它:

{SomeRoute}

对于多个路由,您无法像在函数中那样导出它们,您将收到一个 JSX 错误,指出如果没有包装元素,您就不能拥有相邻的组件。在这种情况下,您必须执行以下操作:

export default (
  <Route>
    <Route path="/about" component={About} />
    <Route path="/services" component={Services} />
  </Route>
);

并使用它:

{ApplicationsRoutes}