React路由,如何理解useLocation钩子?获取当前地址栏URL
发布于 作者:苏南大叔 来源:程序如此灵动~
“react系列的钩子函数,命名都是以use字符串开头的”,这是一个重要信息。本文描述react router里面的useLocation钩子。它有什么用呢?如何使用呢?这就是本文要描述的内容。

苏南大叔的“程序如此灵动”博客,记录苏南大叔的代码编程经验。本文测试环境:nodejs@20.18.0,create-react-app@5.0.1,react-router-dom@6.27.0,react@18.3.1。
官方文档
useLocation是来自react-router-dom的,并不是来自react-dom。它的官方文档是:
官方文字:This hook returns the current location object. This can be useful if you'd like to perform some side effect whenever the current location changes.
当前的locatioin变化的时候,useLocation()的返回值就会发生变化。
最简单测试代码
这里基于create-react-app的默认cra模版,展开叙述。
create-react-app test
cd test
npm i react-router-dom --save
npm i esno nodemon webpack-cli --save-dev然后构造一个最简单的测试代码。参考:index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.createRoot(document.getElementById("root")).render(
<Router>
<App />
</Router>
);App.js:
import React from "react";
import {
BrowserRouter as Router,
Routes,
Route,
useLocation,
NavLink,
} from "react-router-dom";
const Menu = function () {
return (
<>
<style>{"a{margin:2px;border:1px solid black;text-decoration:none;padding:1px;}"}</style>
<style>{"a.active{color:red;font-weight:bold;}"}</style>
<NavLink to="/" state="aaa">Home</NavLink>
<NavLink to="/post/123?s#n" state="uncle sunan">Post123</NavLink>
<NavLink to="/post/456?d#s" state="brother sunan">Post456</NavLink>
</>
);
};
function App() {
let location = useLocation();
console.log(location);
return (
<div>
<Routes>
<Route path="/" element={<Menu />} />
<Route path="/post/:id" element={<Menu />} />
</Routes>
<br /><br />
当前path:{location.pathname}<br/>
当前search:{location.search}<br/>
当前hash:{location.hash}<br/>
当前key:{location.key}<br/>
当前state:{location.state}<br/>
</div>
);
}
export default App;
必须运行在路由标签内部
这个useLocation()必须运行在路由标签包裹的内部代码里面,否则会得到如下错误提示信息:
ERROR
useLocation() may be used only in the context of a <Router> component.
useLocation 返回值
其返回值是个location对象,和常见的document.location是略有不同的。根据官方文档,其返回值对象的主要属性有:
| 名称 | 值 |
|---|---|
| location.hash | The hash of the current URL. |
| location.key | The unique key of this location. |
| location.pathname | The path of the current URL. |
| location.search | The query string of the current URL. |
| location.state | The state value of the location created by <Link state> or navigate. |

结语
本文主要总结了react router的useLocatioin()钩子的最简单用法。更多苏南大叔的react经验文章,请点击: