【问题标题】:How to determine active route in react router如何在反应路由器中确定活动路由
【发布时间】:2016-12-28 09:42:44
【问题描述】:

我有一个使用带有嵌套路由的反应路由器的 Redux 应用程序,如下所示:

<Provider store={store}>
    <Router history={browserHistory}>
        <Route name="sales" path="/" component={App}>
          <IndexRoute name="home" component={Home} />
          <Route name="reports" path="/reports" component={Reports}>
            <IndexRoute name="reports-home" component={ReportsHome} />
          <Route name="report-1" path="/reports/report-1" component={Report1}/>
          <Route name="report-2" path="/reports/report-2" component={Report2}/>
          </Route>
        </Route>
    </Router>
</Provider>

我正在尝试编写一个面包屑组件;所以希望能够确定当前路线。

我已经使用 react router 提供的 withRouter 函数将组件配置为接收路由器:

Breadcrumbs = withRouter(Breadcrumbs);

这给了我一个看起来像这样的路由器对象:

Object {__v2_compatible__: true}
__v2_compatible__: true
createHref: createHref(location, query)
createKey: createKey()createLocation: createLocation(location)
createPath: createPath(location, query)
go: go(n)
goBack: goBack()
goForward: goForward()
isActive: isActive(location)
listen: listen(listener)
listenBefore: listenBefore(hook)
push: push(location)
pushState: ()
registerTransitionHook: registerTransitionHook(hook)
replace: replace(location)
replaceState: ()
setRouteLeaveHook: listenBeforeLeavingRoute(route, hook)
setState: ()
transitionTo: transitionTo(nextLocation)
unregisterTransitionHook: unregisterTransitionHook(hook)
__proto__: Object

我可以用它来确定当前路线吗?有没有更好的办法?

【问题讨论】:

  • isActive 可用于确定位置路径名是否处于活动状态

标签: redux react-router


【解决方案1】:

在 react-router 3.0 版中添加了通过 withRouter 获取位置等。 Dan Abramov 建议升级到 3.0 以与Router 一起使用。从2.7到3.0,只提供你看到的功能。

来源:https://github.com/ReactTraining/react-router/blob/master/CHANGES.md#v300-alpha1

【讨论】:

    【解决方案2】:

    已经有一个模块可以为你做这件事,我相信它叫做react-router-breadcrumbs。不过我没试过。

    如果您想要自定义解决方案,您可以这样做:


    使用this.props.routesthis.props.params 对象。然后,您可以映射 routes 并为每个条目在 params 对象中查找此类键。然后,您可以使用所述参数创建一个字符串。

    请注意,我为每个路由(IndexRoutes 除外)赋予了一个path 属性,因为有时我想为给定页面显示一个自定义名称。例如:

    <Route path="/:productId" name="Start" title="Start" component={StartView} />
    

    这是我的应用程序上的解决方案:

    componentDidMount = () => {
      this._prepareBreadCrumbs(this.props);
    }
    
    componentWillReceiveProps = (newProps) => {
      this._prepareBreadCrumbs(newProps);
    }
    
    _prepareBreadCrumbs = (props) => {
      let {routes, params} = props;
      let breadcrumbPath = "";
      let temp = routes.map(
        (item, i) => {
          if(item.path == null) return null; //if we are visiting an item without a path, ignore it.
          if(i < routes.length-1 && routes[i+1].path != null) {
            let arr = item.path.split(/[:/]|(:\/)/g); //sometimes the path is like "/:product_id/details" so I need to extract the interesting part here.
            arr = arr.map(function(obj) {
              return (obj in params) ? params[obj] : obj; //We now have ":product_id" and "details" - the first one will exist in the "params" object.
            });
            breadcrumbPath += arr.filter(Boolean).join("/") + "/";  //clean out some garbage and add the "/" between paths.
            if(i == 0) return <li key={i}><Link to={breadcrumbPath}>YourSite.com</Link></li>  //If on the root - display the site name
            return <li key={i}><Link to={breadcrumbPath}>{item.name}</Link></li>
          } else {
            document.title = "YourSite.com - " + item.title;  //set the document title if you want
            if(i == 0) return <li key={i} className="active"><span>YourSite.com</span></li>
            return <li key={i} className="active"><span>{item.name}</span></li>
          }
        }
      );
      this.setState({breadcrumbPath: temp});
    }
    
    render() {
      <p>{this.state.breadCrumbPath || ""}</p>
    }
    

    你想把它放在你的顶级 React 组件中。

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2021-02-22
      • 2016-12-13
      • 2017-07-09
      • 2020-07-29
      • 2016-03-23
      • 2021-02-05
      • 2019-08-03
      • 2021-04-20
      相关资源
      最近更新 更多