在 React Router 中,useLocation 是一个 Hook,用于获取当前路由的位置信息(location object)。这个对象包含了当前 URL 的信息,如 pathname、search 和 state 等属性。
以下是如何在 React 组件中使用 useLocation 的基本示例:
import?{?useLocation?}?from?'react-router-dom';function?ComponentUsingLocation()?{??const?location?=?useLocation();??return?(????<div>??????当前路径为:?{location.pathname}??????{/*?如果需要显示查询参数,可以访问location.search?*/}??????{/*?如果在导航时通过state传递了数据,可以通过location.state获取?*/}??????{location.state?&&?<p>传递的数据:?{JSON.stringify(location.state)}</p>}????</div>??);}export?default?ComponentUsingLocation;
在上述代码中:
location.pathname 包含当前路由的路径部分。
location.search 包含 URL 查询字符串(问号后面的部分)。
location.state 在进行导航时可以通过 history.push 或 组件的 state 属性传递的状态对象。
例如,如果从一个地方导航到另一个地方并传递状态:
import?{?useHistory?}?from?'react-router-dom';function?SourceComponent()?{??let?history?=?useHistory();??function?handleClick()?{????history.push('/target',?{?someData:?'example?data'?});??}??return?(????<button?onClick={handleClick}>点击跳转并传递数据</button>??);}
当你使用 /detail/:tid 这样的动态路由时,你可以通过 useLocation 获取到的 pathname 中解析出 tid 的值。这里是一个例子:
import?{?useLocation?}?from?'react-router-dom';function?DetailComponent()?{??const?location?=?useLocation();??//?使用URLSearchParams或者自己编写函数来解析出tid??const?tid?=?location.pathname.split('/').pop();?//?简单的方法,假设tid总是在路径的最后一部分??return?(????<div>??????当前详情ID为:?{tid}??????{/*?根据实际情况渲染详情内容?*/}????</div>??);}export?default?DetailComponent;
但是,更推荐的方式是使用 useParams 钩子从 React Router 中获取动态参数:
import?{?useParams?}?from?'react-router-dom';function?DetailComponent()?{??let?{?tid?}?=?useParams();??return?(????<div>??????当前详情ID为:?{tid}??????{/*?根据实际情况渲染详情内容?*/}????</div>??);}export?default?DetailComponent;
这样,无论你的路由路径如何变化(例如变为 /detail/:tid/something-else),useParams 都能正确地提取出 tid 参数的值。
领取专属 10元无门槛券
私享最新 技术干货