【问题标题】:Loop through an array to create routes in react router循环遍历数组以在反应路由器中创建路由
【发布时间】:2017-10-04 01:49:10
【问题描述】:

我想打一个 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')
);

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

【问题讨论】:

  • 您可以在渲染路由器之前发出get请求。并使用响应生成路由组件。
  • 你有相关文档的链接吗?
  • 你已经尝试过什么?另请注意,JSX 只是 React.createElement(...) facebook.github.io/react/docs/jsx-in-depth.html 的语法糖

标签: javascript arrays reactjs react-router


【解决方案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')
    );
});

【讨论】:

  • 谢谢,我现在试试
  • 如何循环多个层次结构?例如:
猜你喜欢
  • 2021-06-08
  • 2020-01-21
  • 2023-04-11
  • 2017-06-14
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
相关资源
最近更新 更多