如何在react-router-dom v5中使用useLocation获取当前页面URL
获取react-router-dom v5中当前页面的URL路径
直接通过useLocation获取路径
在react-router-dom v5中,useLocation Hook返回的对象包含了当前路由的所有路径相关信息,不需要额外自定义Hook就能直接获取:
import { useLocation } from 'react-router-dom'; function YourComponent() { const location = useLocation(); // 获取不带查询参数的路径 console.log('当前路径:', location.pathname); // 获取包含查询参数和哈希的完整路径 const fullPath = `${location.pathname}${location.search}${location.hash}`; console.log('完整路径:', fullPath); // 若需要完整的浏览器URL(含域名),直接使用window.location.href console.log('完整浏览器URL:', window.location.href); return <div>...</div>; }
类组件或非Hook场景:使用withRouter高阶组件
如果是类组件或者无法直接使用Hook的场景,可以用withRouter高阶组件注入路由信息:
import { withRouter } from 'react-router-dom'; import React from 'react'; class YourClassComponent extends React.Component { componentDidMount() { const { location } = this.props; console.log('当前路径:', location.pathname); console.log('完整路径:', `${location.pathname}${location.search}${location.hash}`); } render() { return <div>...</div>; } } export default withRouter(YourClassComponent);
关于你当前的useQuery Hook
你写的useQuery只是用来解析URL中的查询参数(即?后面的部分),和获取页面路径无关。如果只是需要打印当前导航页面的URL路径,完全不需要这个Hook。
内容的提问来源于stack exchange,提问作者Nimantha Fernando
相关产品推荐
相关产品推荐

