简体   繁体   English

如何为链接动态创建 ReactJs 路由器并为每个链接呈现页面?

[英]How dynamically create ReactJs Router for Links and render a page for each Links?

I have an array of objects( titleUrl ) contains titles and urls that is coming from an API.我有一个对象数组( titleUrl )包含来自 API 的标题和 url。 I used a custom component called MenuLink to create links on the sidebar and the links are populated using Object.keys(titleUrl).map method from the titleUrl array.我使用了一个名为MenuLink的自定义组件在侧边栏上创建链接,并使用titleUrl数组中的Object.keys(titleUrl).map方法填充链接。

What I'm trying to achieve here is, When I click on each menu items it should redirect to a page created using pagerender component which is given as to={{ pathname: "/pagerender"} in the example我在这里想要实现的是,当我单击每个菜单项时,它应该重定向到使用pagerender组件创建的页面,该组件在示例中给出为to={{ pathname: "/pagerender"}

import React from 'react';
import { Link } from "react-router-dom";
import { MenuLink } from "../components/MenuLink";

class CreateLinks extends React.Component{
    render(){
        var titleUrl= [
            {"title1":"url1"},
            {"title2":"url2"},
            {"title3":"url3"},
            ...
            ...
        ];
        return(
            <React.Fragment>
                { 
                    Object.keys(titleUrl).map((item, i) => (
                        <MenuLink key={item} element={Link} to={{ pathname: "/pagerender"} >{ titleUrl[item].title }</MenuLink>
                    ))
                }   
            </React.Fragment>
        )
    }
}

export default CreateLinks;

Partial Solution so far到目前为止的部分解决方案

I was able to create the links dynamically.我能够动态创建链接。

Need to achieve需要达到

Dynamically created routes for these links and when we click on these links, url of the same title (from the array of object) should pass as an argument to the pagerender and using this argument pagerender renders the page为这些链接动态创建的路由,当我们单击这些链接时,相同标题(来自对象数组)的 url 应作为参数传递给pagerender并使用此参数pagerender呈现页面

You could have an array of configs and then map over them:你可以有一个配置数组,然后 map 覆盖它们:

const links = [
  { label: Link1, value: "/link1" },
  { label: Link2, value: "/link2" }
]

const routes = [
  {
    path: "/link1",
    component: Link1
  },
  {
    path: "/link2",
    component: Link2
  }
]

// In render

<Container>
  <Nav>
    {links.map(link => {
      return (
        <MenuLink
          key={link.url}
          element={Link}
          to={{ pathname: link.url }}
        >
          {link.label}>
        </MenuLink>
      );
    })}
  </Nav>
  {routes.map((route) => {
    return (
      <Route
        key={route.path}
        path={route.path}
        exact={route.exact}
        component={route.component}
      />
    );
  })}
</Container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM