【问题标题】:How to read the current URL in the react application如何在 React 应用程序中读取当前 URL
【发布时间】:2018-08-23 15:04:20
【问题描述】:

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

【问题讨论】:

标签: javascript reactjs


【解决方案1】:
window.location.href

返回当前页面的href(URL)

window.location.hostname

返回网络主机的域名

window.location.pathname

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

window.location.protocol

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

【讨论】:

【解决方案2】:

如果您使用 React Router 并且您的组件由 Route 呈现,例如如下所示:

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

该组件将自动接收来自Route 的三个对象,分别名为historylocationmatch。通过它,您可以在location.pathname 下找到您提出的问题。更多信息here

如果您仍在使用 react 路由器并且您的组件没有使用 Route 渲染,您需要使用 withRouter ,它是一个 HOC 并将为您提供 historylocationmatch 作为道具到您的组件。更多信息here

如果你不使用 react 路由器,你需要使用 window.location.pathnamewindow.location.href 或仅使用 location.pathname

【讨论】:

    【解决方案3】:

    如果你使用的是 react 路由器:

    const currentRoute= this.props.location.pathname
    

    否则你可以得到这样的:

    const currentRoute= window.location.pathname
    

    href 会给你完整的 url。

    【讨论】:

      【解决方案4】:

      我们可以使用 react-router-dom 包中的 withRouter 组件从this.props 获取它,方法如下,通过添加类

      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));
      

      输出:

      【讨论】:

        【解决方案5】:

        您可以使用useParams 挂钩来访问您的网址中的值。在 App.jsx 中创建路由时,您将指定输入变量的名称,如下所示:

        <Route 
           path="/search/:searchType/:module/:category/:search/:source"
           exact={true}
           component={yourComponent}
        />
        

        然后您可以使用组件内的useParams 挂钩来访问变量值。

        const {searchType, module, category, search, source} = useParams();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-06
          • 2023-03-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多