react router 获取完整的当前路径名

问题描述 投票:0回答:8

有没有简单的方法返回当前路由器地址。

IE,如果我在页面上,我只想根据反应路由器查看我在哪个页面上。

因此,localhost/admin/users 将返回 admin/users

显然,我可以通过解析位置得到相同的结果,但我想知道React Router是否提供了一个简单的机制来做到这一点,就像它提供params props一样?

reactjs react-router
8个回答
48
投票

如果您使用 1.0 或更高版本,则您的 React 组件中将有

location
作为与路由匹配的 prop。所以你只需输入

this.props.location.pathname

得到你想要的。


26
投票

this.props.location.pathname
仅给出路由路径。

window.location.href
为您提供完整的 URL,如此处建议的那样 https://stackoverflow.com/a/39823749/7560899


17
投票

对于 React 功能组件

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

const MyComponent = () => {
  let location = useLocation();
  ...useState

    useEffect(() => {
    console.log(location.pathname);
  }, []);

  return ();

  };

  export default MyComponent;

还有很多其他选择: https://dev.to/finallynero/hooks-introduced-in-react-router-v5-1-7g8


11
投票

你也可以尝试一下

location.pathname

它可能有效,而其他方法却不起作用,就像对我一样


10
投票

对于使用浏览器窗口对象的非反应、纯基于 JavaScript 的解决方案。 假设当前页面 URL 是这样的

https://hostname:port/path?query
.


window.location.href // returns the full URL 'https://hostname:port/path?query'

window.location.pathname // returns just the 'path' part of the full URL.

window.location.search // returns just the '?query' part of the full URL.

window.location.port // returns the 'port'.

window.location.hostname // returns just the 'hostname' part of the URL.

window.location.host // returns the hostname and port (hostname:port) part of the URL.

window.location.protocol // returns the protocol (https)

window.location.origin // returns the base URL (https://hostname:port)

请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Location 了解更多详细信息。


5
投票

对于 react-router-dom v6

const { pathname } = useLocation();

如果有人需要就导入

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

2
投票

window.location
将给出完整路径。

this.props.location.pathname
- 它可能不会给出完整路径。如果您只需要不带域前缀的 URL 路径,请使用此选项。 (另外,我可能建议使用 context API 在任何子组件中获取它,而不是将其作为 props 传递)

再举一个例子,要实现具有社交分享功能的新组件,您可能需要使用

window.location
而不是
location.pathname


0
投票

如果您想要不带 / 的路径名,则使用它

window.location.pathname.split('/')[1]

© www.soinside.com 2019 - 2024. All rights reserved.