首页 > 解决方案 > 如何在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 两次......我怎样才能避免这种情况?

有人可以指导我吗。谢谢。

标签: javascriptreactjs

解决方案


const crumbs = [];
path.split('/').slice(1).forEach((part, index, parts) => {
    crumbs.push('/' + parts.slice(0, index + 1).join('/'));
});

这看起来比必要的复杂得多。我认为你可以做到

const crumbs = path.split('/');

推荐阅读