【问题标题】:Read the current full URL with React?使用 React 阅读当前的完整 URL?
【发布时间】:2017-02-10 22:19:41
【问题描述】:

如何从 ReactJS 组件中获取完整的 URL?

我认为它应该类似于 this.props.location 但它是 undefined

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    阅读本文我找到了React / NextJs 的解决方案。因为如果我们在 react 或 nextjs 中直接使用 window.location.href 会抛出类似的错误

    服务器错误 ReferenceError: 未定义窗口

    import React, { useState, useEffect } from "react";
    const Product = ({ product }) => {
     const [pageURL, setPageURL] = useState(0);
      useEffect(() => {
        setPageURL(window.location.href);
      })
      return (
         <div>
           <h3>{pageURL}</h3>
          </div>
      );
    };
    

    注意: https://medium.com/frontend-digest/why-is-window-not-defined-in-nextjs-44daf7b4604e#:~:text=NextJS%20is%20a%20framework%20that,is%20not%20run%20in%20NodeJS.

    【讨论】:

      【解决方案2】:

      window.location.href 是您所需要的。但是,如果您使用的是反应路由器,您可能会发现检查 useLocationuseHistory 钩子很有用。 两者都创建了一个具有路径名属性的对象,您可以读取这些属性,并且对一堆其他东西很有用。 Here's a youtube video explaining react router hooks

      两者都会给你你需要的东西(没有域名):

      import { useHistory ,useLocation } from 'react-router-dom';
      const location = useLocation()
      location.pathname
      
      const history = useHistory()
      history.location.pathname
      

      【讨论】:

      • 问题已经说了“with React”,显然window.location.href不是React的方式。
      【解决方案3】:

      只是为了向这个页面添加一点进一步的文档 - 我已经为这个问题苦苦挣扎了一段时间。

      如上所述,获取 URL 的最简单方法是通过 window.location.href

      然后我们可以使用 let urlElements = window.location.href.split('/') 来通过 vanilla Javascript 提取部分 URL

      然后我们将console.log(urlElements) 查看通过在 URL 上调用 .split() 生成的元素数组。

      找到要访问的数组中的哪个索引后,您可以将其分配给变量

      let urlElelement = (urlElements[0])
      

      现在您可以使用 urlElement 的值,这将是您 URL 的特定部分,无论您想要什么。

      【讨论】:

        【解决方案4】:

        要获取当前路由器实例当前位置,您必须使用withRouterreact-router-dom 创建一个高阶组件。否则,当您尝试访问 this.props.location 时,它将返回 undefined

        例子

        import React, { Component } from 'react';
        import { withRouter } from 'react-router-dom';
        
        class className extends Component {
        
              render(){
                   return(
                        ....
                          )
                      }
        }
        
        export default withRouter(className)
        

        【讨论】:

          【解决方案5】:

          正如其他人提到的,首先你需要react-router 包。但是它为您提供的 location 对象包含已解析的 url。

          但是如果你非常想要完整的 url 而不访问全局变量,我相信最快的方法是

          ...
          
          const getA = memoize(() => document.createElement('a'));
          const getCleanA = () => Object.assign(getA(), { href: '' });
          
          const MyComponent = ({ location }) => {
            const { href } = Object.assign(getCleanA(), location);
          
            ...
          

          href 是包含完整网址的那个。

          对于memoize,我通常使用lodash,它的实现方式主要是为了避免不必要地创建新元素。

          P.S.:当然,您不受古老浏览器的限制,您可能想尝试new URL() 的东西,但基本上整个情况或多或少毫无意义,因为您以一种或另一种方式访问​​全局变量。那么为什么不改用window.location.href呢?

          【讨论】:

            【解决方案6】:

            如果您需要 URL 的完整路径,您可以使用 vanilla Javascript:

            window.location.href

            要仅获取路径(减去域名),您可以使用:

            window.location.pathname

            console.log(window.location.pathname); //yields: "/js" (where snippets run)
            console.log(window.location.href);     //yields: "https://stacksnippets.net/js"

            来源:Location pathname Property - W3Schools

            如果你还没有使用“react-router”,你可以使用:

            yarn add react-router

            然后在 "Route" 内的 React.Component 中,您可以调用:

            this.props.location.pathname

            这会返回路径,不包括域名。

            感谢@abdulla-zulqarnain!

            【讨论】:

            • 你可以像路径名window.location.pathname那样做
            【解决方案7】:

            this.props.location is a react-router feature,如果你想使用它,你必须安装它。

            注意:不返回完整的网址。

            【讨论】:

            • 注意:这不会返回完整的url(主机名、协议等)
            【解决方案8】:

            您收到 undefined 是因为您可能拥有 React Router 之外的组件。

            请记住,您需要确保调用 this.props.location 的组件位于 &lt;Route /&gt; 组件中,例如:

            &lt;Route path="/dashboard" component={Dashboard} /&gt;

            然后在仪表板组件中,您可以访问this.props.location...

            【讨论】:

            • 如果您的组件不在&lt;Route /&gt; 内,您可以使用withRouter 高阶组件。
            【解决方案9】:

            window.location.href 是您正在寻找的。

            【讨论】:

            • 请注意,如果配置不正确,可能会在服务器端出现问题。
            • 我需要 window.location 作为客户端功能。因此,我将位置设置为组件 onMount 的状态,以避免在服务器端渲染时出现问题。
            • 它不工作。或请帮助我反应的结构。我用 const ddd = window.location.href;控制台.log(ddd);
            • webpack 会抱怨说'window is not defined'
            • @FranzSee 是的,服务器端代码中没有“窗口”,所以如果这是你的环境,你需要使用 express 或诸如此类的 req.originalUrl 之类的东西。支持 SSR 的各种 react 路由库都有获取此信息的方法。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-01-20
            • 1970-01-01
            相关资源
            最近更新 更多