通过阵列循环来创建反应路由器中的路由
问题描述:
我想要一个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。
答
很简单,只需在加载路线的某个动作中加载数据,并将结果映射到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')
);
});
您可以在渲染路由器之前进行get请求。并使用该响应生成路由组件。 –
你有任何文件的链接吗? – saunders
你已经试过了什么?另请注意,JSX只是React.createElement的语法糖(...)https://facebook.github.io/react/docs/jsx-in-depth.html – alpeware