簡體   English   中英

React router v4 breadcrumbs

[英]React router v4 breadcrumbs

我正在嘗試為v4實現React Router Breadcrumbs

以下是我的路線:

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

我可以在我的應用程序中使用此庫放置面包屑,但是我有以下問題:

闕。 #1:

當我在面包屑中單擊Home時,我可以看到URL更改為http://localhost:8080但是,瀏覽器仍然顯示我所在的頁面。

闕。 #2:

當我從Page1導航到Page2時, 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:無需在應用程序的每個Component內的<Router>元素內包裝<Breadcrumbs ..../>元素。 這可能是因為,在每個組件中包含<Router>元素會導致Router元素的“嵌套”(注意我們在登錄頁面中也有Router標記); 這與react router v4不兼容。

闕。 #2:請參閱此處正式標記的答案(由下面的palsrealm回答)

您的面包屑基於鏈接,它們按設計工作。 要顯示的網頁,您需要設置一個SwitchRoute在IT方面當路徑變化,這將加載相應的組件。 就像是

<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>

這也可以通過HOC來完成,這將允許您使用路由配置對象來設置面包屑。 我在這里開源,但源代碼也在下面:

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,
      })
    }
  />
));

以下組件應返回任何深度的面包屑,主頁除外(原因很明顯)。 您不需要React Router Breadcrumb 我的第一個公開貢獻,所以如果我錯過了一個必不可少的部分,如果有人能指出它會很棒。 我添加了&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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM