React JS / Material UI-路径之间包含动态ID的面包屑

时间:2019-03-11 18:07:35

标签: reactjs react-router material-ui breadcrumbs

我是新来的反应者,并尝试创建路径之间具有动态ID的面包屑。

我对道具的支持是:

const breadcrumbsData = {
  path: "facilities/65743/facilitycontact",
  breadcrumbNameMap: {
    "/facilities": "Facility",
    "/facilities/:facilityId": ":facilityId",
    "/facilities/:facilityId/facilitycontact": "Facility Contact"        
  }
};

呈现面包屑的代码是

<Breadcrumbs arial-label="Breadcrumb">
  {paths.map((path, index) => {
    const url = "/" + paths.slice(0, index + 1).join("/");
    const last = index === paths.length - 1;
    return last ? (
      <Typography color="inherit"> {breadcrumbNameMap[url]} </Typography>
    ) : (
      <Link to={url}>{breadcrumbNameMap[url]}</Link>
    );
  })}
</Breadcrumbs>

我尝试了不同的方法,但是不知道如何做到这一点。它在没有路径之间的ID的情况下完美运行。例如

const breadcrumbsData = {
  path: "facilities/facilityprofile/facilitycontact/workcontact",
  breadcrumbNameMap: {
    "/facilities": "Facility",
    "/facilities/facilityprofile": "Facility Profile",
    "/facilities/facilityprofile/facilitycontact": "Facility Contact"
  }
};

P:S-尝试过“匹配”,但没有成功,我的用例是我正在手动传递道具的路径。

这是完整的代码

Code Sandbox - BreadCrumbs using react and material UI

1 个答案:

答案 0 :(得分:0)

我不确定您为什么需要这种方式,但这是一个临时解决方案。不要直接使用您的breadcrumbsData.breadcrumbNameMap来查找名称。对其进行预处理,并使用简单的字符串替换生成地图。

例如,定义用于预处理地图的实用程序:

generateNameMap = (id, idKey, map) => { 
  // takes the actual id i.e. '65743', 
  // the template key that need to be replaced with i.e. ':facilityId'
  // and the initial map i.e. breadcrumbsData.breadcrumbNameMap
  const clone = {};
  Object.keys(map).forEach(k => {
    clone[k.replace(idKey, id)] = map[k].replace(idKey, id) // replace the template in both key and value with actual id
  })
  return clone;
}

现在定义您的breadcrumbNameMap以使用该实用程序,而不是直接使用breadcrumbsData.breadcrumbNameMap

const breadcrumbNameMap = this.generateNameMap(paths[1], ':facilityId', breadcrumbsData.breadcrumbNameMap);

这是一个演示:

const generateNameMap = (id, idKey, map) => {
    const clone = {};
    Object.keys(map).forEach(k => {
      clone[k.replace(idKey, id)] = map[k].replace(idKey, id)
    })
    return clone;
}


const breadcrumbNameMap = generateNameMap('65743', ':facilityId', {
        "/facilities": "Facility",
        "/facilities/:facilityId": ":facilityId",
        "/facilities/:facilityId/workcontact": "Facility Contact",
        "/facilities/facilityprofile/facilitycontact/": "Work Contact"
});
console.log(breadcrumbNameMap);