10

As on subject how can I get the route name inside the handler? For example:

var routes = <Route handler={App} path="/">
    <Route name="home" path="/home" handler={HomePage} />
    <DefaultRoute handler={HomePage} />
</Route>

Router.run(routes, function(Handler, state) {
  var params = state.params;
  React.render(<Handler params={params}/>, document.body);
});

Now suppose I have a component like this:

class HomePage extends React.Component {
    render() {
        return(<div>MyComponent</div>)
    }
}

how can I get the current route name? To be more specific I want to get the

name="home"

attribute from

<Route name="home" path="/home" handler={HomePage} />
4

3 回答 3

16

在 react-router 0.13 之前,您可以使用this.getRoutes()mixin Router.State

对于 react-router 0.13,您也可以使用它:

var currentRoutes = this.context.router.getCurrentRoutes();
var lastRoute = currentRoutes[currentRoutes.length - 1];
console.log(lastRoute.name);

对于 react-router v2.0.x,您可以使用:

this.props.routes[this.props.routes.length-1]
于 2015-03-28T16:32:08.767 回答
5

反应路由器 4

v4 已从代码库中删除了 JS API,这意味着上述方法将无法继续工作。

新方法是将 props 直接传递给正在渲染的组件,就像您通常在 React 应用程序中使用任何其他组件一样。

import React from 'react';
import { Match, Link, Miss } from 'react-router';
import DocumentMeta from 'react-document-meta';

import MainLayout from './Layouts/MainLayout';
import Homepage from './containers/Homepage/Homepage';
import Game from './containers/Game/Game';
import NotFound from './containers/NotFound/NotFound';

export const routes = {
  homepage: {
    exactly: true,
    pattern: '/',
    label: 'About React Lego',
    component: Homepage
  },
  game: {
    pattern: '/game',
    label: 'Star Wars Trivia',
    component: Game
  }
};

const passPropsToRoute = ({ route, props }) => (
  <span>
    <DocumentMeta title={ route.title } />
    <route.component {...props} routes={route.routes}/>
  </span>
);

const matchWithSubRoutes = (key, i) => {
  const route = routes[key];
  return (<Match { ...route } key={ i } render={(props) => passPropsToRoute({ route, props })} />);
};

export function makeRoutes() {
  return (
    <MainLayout>
      {Object.keys(routes).map(matchWithSubRoutes)}
      <Miss title={`${siteTitle} - Page Not Found`} component={ NotFound } />
    </MainLayout>
  );
}

要在示例应用程序中查看此功能,请查看具有react-router-4 分支的react-lego

于 2016-09-15T09:16:42.330 回答
1

假设我们谈论的是同一个 react-router(当前版本是 2.8.x),您可以通过 直接访问路由this.props.route.path,这将/home用于您的主页(在HomePage组件中)。

链接到文档

编辑:链接已更新。

于 2016-09-14T15:21:52.647 回答