javascript - 如何在reactjs中一次在面包屑中显示面包屑
问题描述
对于特定路线,我想显示面包屑以及代替面包屑的项目信息......我想重用相同的组件面包屑和面包屑。但是,这样做会显示两次项目的信息,因为我映射了面包屑(即 url)。
我想做什么?
class Breadcrumb extends React.PureComponent {
render = () => {
const path = this.props.location.pathname;
const crumbs = [];
path.split('/').slice(1).forEach((part, index, parts) => {
crumbs.push('/' + parts.slice(0, index + 1).join('/'));
});
return (
<div className="classname1">
{crumbs.map((link, i) => {
return (
<Fragment key={link}>
<Crumb
link={link}
item_information={this.props.item_information}
/>
</Fragment>);
})}
</div>
);
};
}
class Crumb extends React.PureComponent {
render = () => {
const link = this.props.link;
let display = [];
let match;
if (link === '/') {
crumb_display = 'home';
} else if (match = link.match(/^\/list\/new$/)) {
crumb_display = 'list new';
} else if (match = link.match(/^\/list\/([^/]+)$/)) {
if (this.props.item_information.length > 0) {
crumb_display = 'items';
} else {
crumb_display = 'list';
} }
}
return (
<div className="classname1">
{this.props.item_information.length > 0 && <somecomponent info={this.props.item_information}/>}
return (
<div className="class">
<Link to={link}>{item.name}</Link>
</div>
);
})}
<div className="class">
<Link to={link}>{crumb_display}</Link>
</div>
};}
考虑 url “/list/id” 现在 crumbs 变量将具有 “/list” 和 “/list/id” 并且由于我们在面包屑组件中有 crumbs.map 渲染 items_information 两次.. 某些列表项没有在这种情况下有项目信息我希望面包屑是列表 list_item_name 并且对于具有信息显示信息代替面包屑的项目,例如 item_information = [{name: 'first'}, {name: 'second'}] 所以它将是第一秒。
使用上面的代码可以正常工作,除了为 url /list/id 渲染 item_information 两次......我怎样才能避免这种情况?
有人可以指导我吗。谢谢。
解决方案
const crumbs = [];
path.split('/').slice(1).forEach((part, index, parts) => {
crumbs.push('/' + parts.slice(0, index + 1).join('/'));
});
这看起来比必要的复杂得多。我认为你可以做到
const crumbs = path.split('/');
推荐阅读
- clips - 如何检索具有特定名称的规则断言的事实?
- javascript - Array.prototype.flat() 在构建 Gatsby 站点时会产生错误
- java - AbstractAnnotationConfigDispatcherServletInitializer 中的 getRootConfigClasses() 和 getServletConfigClasses() 之间的区别
- java - log4j 将日志写入控制台和文件
- javascript - 如何修复Javascript中输入的偶数的总和?
- python - 如何检测嘈杂的线条图像中的线条?
- javascript - 我的显示建议代码在 Firefox 上运行良好,但不适用于 Chrome 和 IE
- node.js - 即使使用正文解析器也请求正文为空
- java - 从方法 :: org.mockito.exceptions.misusing.MissingMethodInvocationException 调用另一个方法
- python - 如何编写 python 脚本对 Azure DevOps REST API 进行身份验证并获取访问令牌?