循环遍历数组以在react-router中创建路由

IT技术 javascript arrays reactjs react-router
2021-05-25 19:09:00

我想点击一个 API,它会返回我需要用于react网站的网站的所有路由。

我不完全确定如何去做,甚至谷歌一个例子。

我的代码如下所示:

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')
);

Route path="/" 下的所有内容都需要来自 API。

1个回答

很简单,只需在某些加载路线的操作中加载数据,并在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')
    );
});