如何在反应路由器中将子路由定义为反应组件?
How to define child routes as react components in react-router?
我有 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
的路由将被添加到主路由器,因此 ApplicationsHome 将为路径 /applications
呈现
不幸的是,事实并非如此。我收到错误:
Location "/applications" did not match any routes
对我来说,这样组成 Router 的方法似乎行不通,但我不明白什么是正确的方法。
对于单一路由,您可以将路由导出为 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}
一般来说,当你这样做时,你应该考虑使用 PlainRoute
语法而不是 JSX 语法,然后在父路由上使用 getChildRoutes
来解析子路由,根据 huge-apps 示例:https://github.com/rackt/react-router/tree/master/examples/huge-apps
这样您就可以轻松地配置 code-splitting 和动态路由。
我有 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
的路由将被添加到主路由器,因此 ApplicationsHome 将为路径 /applications
不幸的是,事实并非如此。我收到错误:
Location "/applications" did not match any routes
对我来说,这样组成 Router 的方法似乎行不通,但我不明白什么是正确的方法。
对于单一路由,您可以将路由导出为 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}
一般来说,当你这样做时,你应该考虑使用 PlainRoute
语法而不是 JSX 语法,然后在父路由上使用 getChildRoutes
来解析子路由,根据 huge-apps 示例:https://github.com/rackt/react-router/tree/master/examples/huge-apps
这样您就可以轻松地配置 code-splitting 和动态路由。