循环通过数组以创建路线 [英] Loop through an array to create routes

查看:20
本文介绍了循环通过数组以创建路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有单独的routes.js:

export const routes = [
    {pathname: "/", exact: true, name: "Home Page", id: "home", component: Home},
    {pathname: "/about", exact: true, name: "About Us", id: "about", component: About},
    {pathname: "/services", exact: true, name: "Services", id: "services", component: Services},
    {pathname: "/portfolio", exact: true, name: "Portfolio", id: "portfolio", component: Portfolio},
    {pathname: "/careers", exact: true, name: "Careers", id: "careers", component: Careers},
    {pathname: "/partners", exact: true, name: "Partners", id: "partners", component: Partners},
    {pathname: "/contact", exact: true, name: "Contact Us", id: "contact", component: Contact},
    {pathname: "/blog", exact: true, name: "Blog", id: "blog", component: Blog},
    {pathname: "/not-found", exact: true, name: "Not Found", id: "not-found", component: NotFound},
];

导入到我的App.js中:

import { routes } from './routes.js';

const App = (props) => {     

  return (
    <div className='app-wrapper'>
      <Header />
      <BgVideo />          
        <Switch>
          <Route path={routes[0].pathname} exact component={routes[0].component} />
          <Route path={routes[1].pathname} exact component={routes[1].component} />
          <Route path={routes[2].pathname} exact component={routes[2].component} />
          <Route path={routes[3].pathname} exact component={routes[3].component} />
          <Route path={routes[4].pathname} exact component={routes[4].component} />
          <Route path={routes[5].pathname} exact component={routes[5].component} />
          <Route path={routes[6].pathname} exact component={routes[6].component} />
          <Route path={routes[7].pathname} exact component={routes[7].component} />  
          <Route path={routes[8].pathname} exact component={routes[8].component} />                           

          <Redirect to='/not-found' />
        </Switch>
    </div>
  );
};

现在工作正常,但我希望循环遍历路由数组,并且不重复<Route/>9次。

推荐答案

<Switch>
  {routes.map(route =>
     <Route key={route.id} path={route.pathname} exact component={route.component} />
  )}
  <Redirect to='/not-found' />
</Switch>

这是基本的Reaction内容,我建议您应该学习入门教程。

这篇关于循环通过数组以创建路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆