javascript 如何在react应用中读取当前的URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51988873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read the current URL in the react application
提问by Phani
I would like read and print the current URL in the react application. Right now i am using "window.location.pathname" to read the URL but would like to know if there is a better way or some react way to read the URL
我想在反应应用程序中读取和打印当前的 URL。现在我正在使用“window.location.pathname”来读取 URL,但想知道是否有更好的方法或某种反应方式来读取 URL
回答by Ashley Fernandes
window.location.href
returns the href (URL) of the current page
返回当前页面的href(URL)
window.location.hostname
returns the domain name of the web host
返回网络主机的域名
window.location.pathname
returns the path and filename of the current page
返回当前页面的路径和文件名
window.location.protocol
returns the web protocol used (http: or https:)
返回使用的网络协议(http: 或 https:)
回答by a_m_dev
if you are using React Router and your component is rendered by a Routelike below for example:
如果您使用的是 React Router 并且您的组件是由Route以下示例呈现的:
<Route exact path='/' component={HomeComponent}/>
that component will automatically receive three objects from Routenamed history, locationand matchrespectively. by that you can find what you asked under location.pathname. more info here
该组件可以自动从三个对象Route命名history,location并match分别。通过它,您可以找到您在 下询问的内容location.pathname。更多信息在这里
if you still using react router and your component is not been rendered with Route, you need to use withRouter, which is a HOC and will give you history, locationand matchas props to your component. more info here
如果您仍在使用 react 路由器并且您的组件未使用 进行渲染Route,则需要使用withRouter,这是一个 HOC 并将为您提供history,location并match作为组件的道具。更多信息在这里
if you are not using react router you gonna need to use window.location.pathnameor window.location.hrefor only location.pathname
如果你没有使用你的路由器会作出反应需要使用window.location.pathname或window.location.href或只location.pathname
回答by Sakhi Mansoor
If you are using react router:
如果您使用的是反应路由器:
const currentRoute= this.props.location.pathname
else you can get this like:
否则你可以得到这样的:
const currentRoute= window.location.pathname
href will give you complete url.
href 会给你完整的网址。

