如何在react应用中读取当前的URL

IT技术 javascript reactjs
2021-05-21 00:35:45

我想在react应用程序中读取和打印当前的 URL。现在我正在使用“window.location.pathname”来读取 URL,但想知道是否有更好的方法或某种react方式来读取 URL

4个回答
window.location.href

返回当前页面的href(URL)

window.location.hostname

返回网络主机的域名

window.location.pathname

返回当前页面的路径和文件名

window.location.protocol

返回使用的网络协议(http: 或 https:)

如果您使用的是 React Router 并且您的组件是由Route以下示例呈现的

<Route exact path='/' component={HomeComponent}/>

该组件可以自动从三个对象Route命名historylocationmatch分别。通过它,您可以找到您在 下询问的内容location.pathname更多信息在这里

如果您仍在使用 react 路由器并且您的组件未使用 进行渲染Route,则需要使用withRouter,这是一个 HOC 并将为您提供history,locationmatch作为组件的props。更多信息在这里

如果你没有使用你的路由器会作出react需要使用window.location.pathnamewindow.location.href或只location.pathname

如果您使用的是react-router:

const currentRoute= this.props.location.pathname

否则你可以得到这样的:

const currentRoute= window.location.pathname

href 会给你完整的网址。

我们可以通过在类中添加以下方式this.props使用来自react-router-dom包的withRouter组件 来获取它

import React from 'react';

import { connect } from 'react-redux';
import { Switch, Route, withRouter } from 'react-router-dom';


class Application extends React.PureComponent {
  
  render() {
    console.log(this.props)
    this.props.location.pathname // we will get the pathname

    return (
      <div className='application'>
        {Hi}
      </div>
    );
  }
}


export default connect(mapStateToProps, actions)(withRouter(Application));

输出:

在此处输入图片说明