React Router-制作面包屑

时间:2018-09-19 21:30:36

标签: reactjs react-router

我正试图在Breadcrumbs的帮助下制作一个react-router-dom组件,但我有几个问题

说我给了一条看起来像这样的路线:

breadcrumbRoutes: [
    {
      path: '/devicePolicies',
      exact: true,
      name: "Device Policies",
      main: () => <h2>Device Policies View</h2>
    },
    {
      path: '/devicePolicies/controlPanel',
      exact: true,
      name: "Control Panel",
      main: () => <h2>Control Panel View</h2>
    },
    {
      path: '/devicePolicies/controlPanel/settings',
      exact: true,
      name: "Settings",
      main: () => <h2>Settings View</h2>
    }
  ]

当前,我的Breadcrumbs组件将使其呈现为Device Policies/Control Panel/Settings。但是,它没有正确呈现与最新路径/devicePolicies/controlPanel/settings关联的正确组件。例如,代替呈现settings组件,它呈现Home组件。

Breadcrumbs.js

Class Breadcrumbs extend Component

insertBreadcrumbs() {
var routes = this.props.routes;

    return (
      <div style={{display: 'flex'}}>
          <ul className="breadcrumb">
            { this.insertListElement(routes) }
          </ul>
          {routes.map((route) => (
             <Route
                  key={route.path}
                  path={route.path}
                  exact={route.exact}
                  component={route.main}
             />
          ))}
     </div>
    );
}
render() {
    return (
        <Router>
              { this.insertBreadcrumbs() }
        </Router>
    );
}

App.js

<Breadcrumbs 
        name="breadcrumbRoutes"
        routes={this.state.breadcrumbRoutes}
        onChange={this.handleChange}
 />

如何使加载的视图始终成为路径的最后一部分?在此示例中,我想加载settings

的组件

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我知道了我的问题所在。原来,我是错误地测试了行为。我试图强迫路由器将位置设置为settings,而不是制作具有Link的{​​{1}}。通过插入to="devicePolicies/controlPanel/settings,我可以正确将路由器位置设置为Link,然后正确呈现相应的组件。谢谢大家的投入!