React Router v4 - 如何获取当前路由?

Rap*_*nah 121 reactjs react-router react-router-v4

我想显示一个title<AppBar />某种方式从当前路线传入的内容.

在React Router v4中,如何<AppBar />才能将当前路由传递给它的title道具?

  <Router basename='/app'>
    <main>
      <Menu active={menu} close={this.closeMenu} />
      <Overlay active={menu} onClick={this.closeMenu} />
      <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
      <Route path='/customers' component={Customers} />
    </main>
  </Router>
Run Code Online (Sandbox Code Playgroud)

有没有办法通过从自定义自定义标题prop<Route />

v21*_*103 278

在 react-router 的 5.1 版本中有一个名为useLocation的钩子,它返回当前的位置对象。这在您需要知道当前 URL 的任何时候都可能有用。

import { useLocation } from 'react-router-dom'

function HeaderView() {
  const location = useLocation();
  console.log(location.pathname);
  return <span>Path : {location.pathname}</span>
}

Run Code Online (Sandbox Code Playgroud)

  • 请注意,这只能在 Router DOM 内部使用(即 chid 组件,而不是在使用 Router 的类/功能组件中)。这可能是显而易见的,但对于像我这样的新手来说却不是:-)我一直收到错误“useContext is undefined” (36认同)
  • 他们特别要求“React Router ***v4***”,而不是 v5。 (3认同)
  • @eriegz,这是真的,但这也是搜索“获取当前路径名反应路由器”时的第一个谷歌结果,所以这个答案显示在顶部是一件非常好的事情 (3认同)
  • 为什么不将 location 设置为 `const` 而不是 `let`,因为我们知道它在这种情况下不会改变? (2认同)

小智 167

在反应路由器4中,当前路由在 - this.props.location.pathname.得到 this.props并验证.如果你还没有看到, location.pathname那么你应该使用装饰器withRouter.

这可能看起来像这样:

import {withRouter} from 'react-router-dom';

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这并非总是如此:使用react-router4,如果您的组件在某个嵌套路由(稍后扩展路径)的更高级别上呈现,则WithRouter内的location.pathname将与`window.location不同. pathname` (12认同)
  • 我们如何在 React 组件之外以编程方式获取它? (4认同)
  • 此解决方案不提供如何在包含 &lt;Router&gt; 本身的组件中使用这些道具。 (2认同)

low*_*ler 58

如果使用的是反应的模板,在您结束反应文件看起来是这样的:export default SomeComponent你需要使用高次成分(通常被称为一个"特别") withRouter.

首先,您需要withRouter像这样导入:

import {withRouter} from 'react-router-dom';
Run Code Online (Sandbox Code Playgroud)

接下来,您将要使用 withRouter.您可以通过更改组件的导出来完成此操作.很可能你想从改变export default ComponentNameexport default withRouter(ComponentName).

然后你可以从道具获得路线(和其他信息).具体而言,location,match,和history.吐出路径名的代码是:

console.log(this.props.location.pathname);
Run Code Online (Sandbox Code Playgroud)

这里有一个附加信息的好文章:https://reacttraining.com/react-router/core/guides/philosophy


Ale*_*Kim 58

react-router v5有一个叫做useLocation的hook ,不需要HOC什么的,非常简洁方便。

import { useLocation } from 'react-router-dom';

const ExampleComponent: React.FC = () => {
  const location = useLocation();  

  return (
    <Router basename='/app'>
      <main>
        <AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
      </main>
    </Router>
  );
}
Run Code Online (Sandbox Code Playgroud)


小智 32

这是使用阅读更多的解决方案history

import { createBrowserHistory } from "history";

const history = createBrowserHistory()
Run Code Online (Sandbox Code Playgroud)

路由器内部

<Router>
   {history.location.pathname}
</Router>
Run Code Online (Sandbox Code Playgroud)

  • 对于我们这些走在反应函数道路上的人来说,这个答案是最有意义的。那些“this.props....”对我们来说只是噪音。 (4认同)

小智 21

Con Posidielov是否说过,当前路线存在于this.props.location.pathname.

但是如果你想匹配一个更具体的字段,比如一个键(或一个名字),你可以使用matchPath来查找原始路由引用。

import { matchPath } from `react-router`

const routes = [{
  key: 'page1'
  exact: true,
  path: '/page1/:someparam/',
  component: Page1,
},
{
  exact: true,
  key: 'page2',
  path: '/page2',
  component: Page2,
},
]

const currentRoute = routes.find(
  route => matchPath(this.props.location.pathname, route)
)

console.log(`My current route key is : ${currentRoute.key}`)
Run Code Online (Sandbox Code Playgroud)


小智 9

我认为React Router(v4)的作者刚刚添加了withRouter HOC来安抚某些用户.但是,我认为更好的方法是使用渲染道具并制作一个简单的PropsRoute组件来传递这些道具.这更容易测试,因为它没有像路由器那样"连接"组件.将一堆嵌套组件包含在withRouter中,它不会很有趣.另一个好处是你也可以使用这个传递你希望路线的任何道具.这是使用render prop的简单示例.(几乎是他们网站上的确切示例https://reacttraining.com/react-router/web/api/Route/render-func)(src/components/routes/props-route)

import React from 'react';
import { Route } from 'react-router';

export const PropsRoute = ({ component: Component, ...props }) => (
  <Route
    { ...props }
    render={ renderProps => (<Component { ...renderProps } { ...props } />) }
  />
);

export default PropsRoute;
Run Code Online (Sandbox Code Playgroud)

用法:(通知获取路线参数(match.params)你可以使用这个组件,那些将被传递给你)

import React from 'react';
import PropsRoute from 'src/components/routes/props-route';

export const someComponent = props => (<PropsRoute component={ Profile } />);
Run Code Online (Sandbox Code Playgroud)

还要注意你也可以通过这种方式传递任何额外的道具

<PropsRoute isFetching={ isFetchingProfile } title="User Profile" component={ Profile } />
Run Code Online (Sandbox Code Playgroud)

  • 有什么办法可以将这种解决方案变成代码笔?我想使用更正确的解决方案,但我真的不知道如何实现。 (3认同)

小智 5

添加

import {withRouter} from 'react-router-dom';
Run Code Online (Sandbox Code Playgroud)

然后更改您的组件导出

export default withRouter(ComponentName)
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下命令直接在组件本身内访问路由(无需接触项目中的其他任何内容):

window.location.pathname
Run Code Online (Sandbox Code Playgroud)

2020 年 3 月测试:“版本”:“5.1.2”

  • 不确定这个。当然,它给出了当前的路径名,但如果我导航到新页面,它不会改变。 (3认同)