react-router-dom 从url中获取参数方法

 

📌 方法 1:使用 useParams 获取动态路由参数

如果你的路由是动态路径参数(即 :id 这种形式),可以用 useParams 来获取。

🛠 示例

tsx
import { useParams } from "react-router-dom"; const UserProfile = () => { const { userId } = useParams(); // 获取 URL 参数 return <h1>用户 ID: {userId}</h1>; };

📌 路由配置

tsx
<Route path="/user/:userId" element={<UserProfile />} />

如果访问 /user/123,则 useParams() 返回:

ts
{ userId: "123" }

📌 方法 2:使用 useLocation 获取查询参数

如果 URL 形如 /search?query=react,可以用 useLocation 来解析查询参数。

🛠 示例

tsx
import { useLocation } from "react-router-dom"; const SearchPage = () => { const location = useLocation(); const searchParams = new URLSearchParams(location.search); const query = searchParams.get("query"); // 获取 ?query=xxx 的值 return <h1>搜索关键词: {query}</h1>; };

📌 访问的 URL

bash
/search?query=react

📌 获取的结果

ts
query = "react"

🚀 总结

方法适用场景示例
useParams() 获取 :id 这种动态路由参数 /user/:userId
useLocation() + URLSearchParams 获取查询参数 ?key=value /search?query=react

你是想解析哪种类型的参数?😃

 
 
 
 
posted @ 2025-03-11 22:31  走走停停走走  Views(486)  Comments(0)    收藏  举报