好,所以我有以下面包屑脚本,该脚本为我的React应用程序生成面包屑。一切正常,直到我添加第二个参数,如下所示。 实际的路由工作正常,只是显示面包屑。
我正在使用react&react-router-dom v6.4.1
引发“密钥”错误
/Sites/SiteDashboard/${this.props.match.params.id}/SiteDevices/EditDevice/${row.id}
面包屑
/Sites/SiteDashboard/:id/SiteDevices/EditDevice/:deviceid
单个参数可以正常工作
'/Sites/SiteDashboard/:id': params => params.id,
已经尝试过,同样的错误
'/SiteDevices/:deviceid': params => params.deviceid,
有2个参数我得到了错误,如下面的注释所示...
我需要有关如何在我的路线中使用两个参数的建议,而又不会在第二个参数上出现此“关键”错误。谢谢。
import React from 'react';
import Route from 'route-parser';
import { Link, withRouter } from 'react-router-dom';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
const isFunction = value => typeof value === 'function';
const getPathTokens = pathname => {
const paths = ['/'];
if (pathname === '/') return paths;
pathname.split('/').reduce((prev, curr) => {
const currPath = `${prev}/${curr}`;
paths.push(currPath);
return currPath;
});
return paths;
};
function getRouteMatch(routes, path) {
return Object.keys(routes)
.map(key => {
const params = new Route(key).match(path);
return {
didMatch: params !== false,
params,
key
};
})
.filter(item => item.didMatch)[0];
}
function getBreadcrumbs({ routes, match, location }) {
const pathTokens = getPathTokens(location.pathname);
return pathTokens.map((path, i) => {
const routeMatch = getRouteMatch(routes, path);
///////////second params error
///////////Uncaught TypeError: Cannot read property 'key' of undefined
const routeValue = routes[routeMatch.key];
const name = isFunction(routeValue)
? routeValue(routeMatch.params)
: routeValue;
return { name, path };
});
}
function Breadcrumbs({ routes, match, location }) {
const breadcrumbs = getBreadcrumbs({ routes, match, location });
return (
<div>
{' '}
{breadcrumbs.map((breadcrumb, i) =>
<span key={breadcrumb.path}>
<Link to={breadcrumb.path}>
{breadcrumb.name}
</Link>
{i < breadcrumbs.length - 1 ? <FontAwesomeIcon icon={['fas', 'caret-right']} /> : ''}
</span>
)}
</div>
);
}
export default withRouter(Breadcrumbs);