2017-05-05 88 views
3

我想要一個API,它會將我需要的網站的所有路由返回給反應網站。通過陣列循環來創建反應路由器中的路由

我不完全確定如何去做,甚至谷歌的例子。

我的代碼如下所示:

ReactDOM.render(
<Router history={browserHistory}> 
    <Route path="/" component={App}> 
     <IndexRoute pageId={5} background="" component={Home}/> 
     <Route path="/your-journey" background="" pageId={7} component={YourJourney}/> 
     <Route path="/designed-for-you" background="" pageId={6} component={DesignedForYou}/> 
     <Route path="/join-us" background="" pageId={1} component={JoinUs}/> 
     <Route path="/get-in-touch" background="no-hero-image" pageId={4} component={GetInTouch}/> 
     <Route path="/legal-and-compliance" background="no-hero-image" pageId={8} component={Legal}/> 
     <Route path="/privacy" background="no-hero-image" pageId={9} component={Privacy}/> 
    </Route> 
    </Router>, 
    document.getElementById('root') 
); 

這裏的一切路由路徑下=「/」需要來自API。

+0

您可以在渲染路由器之前進行get請求。並使用該響應生成路由組件。 –

+0

你有任何文件的鏈接嗎? – saunders

+0

你已經試過了什麼?另請注意,JSX只是React.createElement的語法糖(...)https://facebook.github.io/react/docs/jsx-in-depth.html – alpeware

回答

4

很簡單,只需在加載路線的某個動作中加載數據,並將結果映射到ReactDOM.render函數中。它看起來像這樣:

// This just maps the component string names (keys) to actual react components (values) 
const COMPONENT_MAP = { 
    'Privacy': Privacy, // quotes are not necessary, just illustrating the difference a bit more 
    // ... other mappings 
} 

// Some asynch action that loads the routes from your API 
getRoutes().then((routes) => { 
    ReactDOM.render(
     <Router history={browserHistory}> 
     <Route path="/" component={App}> 
      <IndexRoute pageId={5} background="" component={Home}/> 
      {routes.map((r) => { 
      return <Route path={r.path} background={r.bg} pageId={r.pageId} component={COMPONENT_MAP[r.component]}/> 
      }} 
     </Route> 
     </Router>, 
     document.getElementById('root') 
    ); 
}); 
+0

謝謝,我現在就試試這個 – saunders

+0

這工作了一個治療!謝謝!! – saunders

+0

如何循環多個層次的層次結構?用於離: <路由器歷史= {browserHistory}> <路由路徑= 「/」 成分= {應用}> <路由路徑=「/ your-journey」background =「」pageId = {7} component = {YourJourney}>