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

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


当前回答

location是一个react-router特性,如果你想使用它,你必须安装它。

注意:不返回完整的url。

其他回答

为了获得当前路由器实例或当前位置,你必须从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

Window.location.href是你要找的。

只是在这个页面上添加一些进一步的文档-我已经与这个问题斗争了一段时间。

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

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

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

一旦找到想要访问数组中的哪个索引,就可以将其赋值给一个变量

let urlElelement = (urlElements[0])

现在你可以使用urlElement的值,它将是URL的特定部分,无论你想在哪里。