React router v4 breadcrumbs

时间:2017-10-11 12:47:39

标签: javascript reactjs breadcrumbs react-router-v4

我正在尝试实施React Router Breadcrumbs for v4

以下是我的路线:

    const routes = {
      '/': 'Home',
      '/page1': 'Page 1',
      '/page2': 'Page 2'
    };

我可以在我的应用程序中使用这个库添加面包屑,但是我有以下问题:

阙。 #1:

当我点击我的面包屑中的Home时,我可以看到网址更改为http://localhost:8080但是,浏览器仍显示我所在的页面。

阙。 #2:

当我从第1页导航到第2页时,urlhttp://localhost:8080/page1更改为http://localhost:8080/page2

因此,面包屑显示更改为Home / Page 2而非更改为Home / Page 1 / Page 2

我知道这可能是因为url在主机名后面只有/page2。但是,我可以实现如下显示:Home / Page 1 / Page 2

以下是我的主App.jsx中的代码:

<Router>
  <div>
    <Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
    <Route exact path="/" component={LandingPage}/>
    <Route path="/page1" component={Page1}/>
    <Route path="/page2" component={Page2}/>
  </div>
</Router>

如果我使用下面的内容来满足面包屑的需要,那么我的page2会在page1下面呈现:

    <Router>
      <div>
        <Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
        <Route exact path="/" component={LandingPage}/>
        <Route path="/page1" component={Page1}/>
        <Route path="/page1/page2" component={Page2}/>
      </div>
    </Router>

答案:

阙。 #1:无需在应用程序的每个组件内的<Breadcrumbs ..../>元素内包装<Router>元素。这可能是因为,在每个组件中包含<Router>元素会导致&#34;嵌套&#34; Router个元素(注意我们在着陆页中也有Router个标记);这与react router v4无效。

阙。 #2:请参阅此处正式标记的答案(由以下 palsrealm 回答)

3 个答案:

答案 0 :(得分:2)

您的面包屑基于链接,它们按设计工作。要显示页面,您需要设置一个Switch,其中包含Route,这将在路径更改时加载相应的组件。像

这样的东西
<Switch> 
    <Route path='/' component={Home}/>
    <Route path='/page1' component={Page1}/>
    <Route path='/page2' component={Page2}/>
</Switch>

如果您希望面包屑显示Home/Page1/Page2,则routes应为'/page1/page2' : 'Page 2'Route也应相应更改。

修改:您的Router应为

 <Router>
      <div>
        <Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
        <Switch>
        <Route exact path="/" component={LandingPage}/>
        <Route exact path="/page1" component={Page1}/>
        <Route path="/page1/page2" component={Page2}/>
        </Switch>
      </div>
    </Router>

答案 1 :(得分:1)

这也可以通过HOC来完成,它允许您使用路由配置对象来设置面包屑。我已开源here,但源代码也在下面:

Breadcrumbs.jsx

import React from 'react';
import { NavLink } from 'react-router-dom';
import { withBreadcrumbs } from 'withBreadcrumbs';

const UserBreadcrumb = ({ match }) =>
  <span>{match.params.userId}</span>; // use match param userId to fetch/display user name

const routes = [
  { path: 'users', breadcrumb: 'Users' },
  { path: 'users/:userId', breadcrumb: UserBreadcrumb},
  { path: 'something-else', breadcrumb: ':)' },
];

const Breadcrumbs = ({ breadcrumbs }) => (
  <div>
    {breadcrumbs.map(({ breadcrumb, path, match }) => (
      <span key={path}>
        <NavLink to={match.url}>
          {breadcrumb}
        </NavLink>
        <span>/</span>
      </span>
    ))}
  </div>
);

export default withBreadcrumbs(routes)(Breadcrumbs);

withBreadcrumbs.js

import React from 'react';
import { matchPath, withRouter } from 'react-router';

const renderer = ({ breadcrumb, match }) => {
  if (typeof breadcrumb === 'function') { return breadcrumb({ match }); }
  return breadcrumb;
};

export const getBreadcrumbs = ({ routes, pathname }) => {
  const matches = [];

  pathname
    .replace(/\/$/, '')
    .split('/')
    .reduce((previous, current) => {
      const pathSection = `${previous}/${current}`;

      let breadcrumbMatch;

      routes.some(({ breadcrumb, path }) => {
        const match = matchPath(pathSection, { exact: true, path });

        if (match) {
          breadcrumbMatch = {
            breadcrumb: renderer({ breadcrumb, match }),
            path,
            match,
          };
          return true;
        }

        return false;
      });

      if (breadcrumbMatch) {
        matches.push(breadcrumbMatch);
      }

      return pathSection;
    });

  return matches;
};

export const withBreadcrumbs = routes => Component => withRouter(props => (
  <Component
    {...props}
    breadcrumbs={
      getBreadcrumbs({
        pathname: props.location.pathname,
        routes,
      })
    }
  />
));

答案 2 :(得分:0)

以下组件应返回任何深度的痕迹,除了在主页上(出于显而易见的原因)。您不需要 React Router Breadcrumb 。我的第一个公开贡献,所以如果我错过了一个必不可少的部分,如果有人能指出它会很棒。我为crumbs拆分添加了&raquo;,但您可以明显更新它以匹配您需要的内容。

import React from 'react'
import ReactDOM from 'react-dom'
import { Route, Link } from 'react-router-dom'
// styles
require('./styles/_breadcrumbs.scss')

// replace underscores with spaces in path names
const formatLeafName = leaf => leaf.replace('_', ' ')

// create a path based on the leaf position in the branch
const formatPath = (branch, index) => branch.slice(0, index + 1).join('/')

// output the individual breadcrumb links
const BreadCrumb = props => {
  const { leaf, index, branch } = props,
    leafPath = formatPath(branch, index),
    leafName = index == 0 ? 'home' : formatLeafName(leaf),
    leafItem =
      index + 1 < branch.length 
        ? <li className="breadcrumbs__crumb">
          <Link to={leafPath}>{leafName}</Link>
          <span className="separator">&raquo;</span>
        </li>
        : <li className="breadcrumbs__crumb">{leafName}</li>
  // the slug doesn't need a link or a separator, so we output just the leaf name

  return leafItem
}

const BreadCrumbList = props => {
  const path = props.match.url,
    listItems =
      // make sure we're not home (home return '/' on url)
      path.length > 1
      && path
        // create an array of leaf names
        .split('/')
        // send our new array to BreadCrumb for formating
        .map((leaf, index, branch) => 
          <BreadCrumb leaf={leaf} index={index} branch={branch} key={index} />
        )

  // listItem will exist anywhere but home
  return listItems && <ul className="breadcrumbs">{listItems}</ul>
}

const BreadCrumbs = props => 
  <Route path="/*" render={({ match }) => <BreadCrumbList match={match} />} />


export default BreadCrumbs