我如何从一个ReactJS组件中获得完整的URL ?

我认为它应该是这样的。props。location但它是未定义的


当前回答

你得到的是未定义的,因为你可能有React路由器之外的组件。

记住,你需要确保调用this.props.location的组件位于<Route />组件中,如下所示:

<Route path="/仪表盘"抱怨={仪表盘}/>

然后在Dashboard组件中,你可以访问this.props.location…

其他回答

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

window.location.href

要获得路径(减去域名),你可以使用:

window.location.pathname

console.log (window.location.pathname);//输出:"/js"(代码段运行的地方) console.log (window.location.href);/ /收益率:“https://stacksnippets.net/js”

来源:位置路径名属性- W3Schools

如果你还没有使用"react-router",你可以使用以下方法安装它:

纱线添加反应路由器

然后在React中。组件,你可以调用:

this.props.location.pathname

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

谢谢@abdulla-zulqarnain !

为了获得当前路由器实例或当前位置,你必须从react-router-dom中使用withRouter创建一个高级组件。否则,当你试图访问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)

看了这篇文章,我找到了React / NextJs的解决方案。因为如果我们直接在react或nextjs中使用window。location。href它会抛出错误

服务器错误 ReferenceError:没有定义window

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: ~:文本= NextJS % 20 % 20 % 20框架% 20,% 20不是% 20在% 20 nodejs运行% 20。

普通JS:

window.location.href // Returns full path, with domain name
window.location.origin // returns window domain url Ex : "https://stackoverflow.com"
window.location.pathname // returns relative path, without domain name

使用react-router

this.props.location.pathname // returns relative path, without domain name

使用react Hook

const location = useLocation(); // React Hook
console.log(location.pathname); // returns relative path, without domain name

正如其他人提到的,首先你需要一个反应路由器包。但它提供给你的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包含一个完整的url。

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

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