簡體   English   中英

如何在反應路由器中將子路線定義為反應組件?

[英]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路由將添加到主路由器,因此將為路徑/applications呈現ApplicationsHome。

不幸的是,事實並非如此。 我收到錯誤消息:

Location "/applications" did not match any routes

對我來說,這種構成Router的方法似乎行不通,但是我不明白什么是正確的方法。

通常,在執行此操作時,應考慮使用PlainRoute語法而不是JSX語法,然后按照巨型應用示例,在父路由上使用getChildRoutes來解析子路由: 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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM