React Router 6 获取路由参数

发布于:2025-08-31 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、params参数

传递params参数

路由链接(携带参数):<Link to='/demo/test/18'}>详情</Link>

注册路由(声明接收):<Route path="/demo/test/:id" component={Test}/>

获取params参数

import React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';
import User from './pages/User.jsx'

function ProfilePage() {
  // 获取URL中携带过来的params参数,"/demo/test/:id"
  let { id } = useParams();
  
  return <>{id}</>
}

二、search参数

传递search参数

路山链接(携带参数):<Link to='/demo/test?name=tom&age=18'}>详情</Link>

注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>

获取search参数

import React from 'react'
import {useSearchParams} from 'react-router-dom'

export default function Detail() {
	const [search,setSearch] = useSearchParams()
	const name= search.get('name')
	const age= search.get('age')
	return (
		<ul>
			<li>
				<button onClick={()=>setSearch('name=哈哈&age=11')}>点我更新一下收到的search参数</button>
			</li>
			<li>名字:{name}</li>
			<li>年龄:{age}</li>
		</ul>
	)
}

三、state参数

传递state参数

路由锋按(携带参数):<Link to={{path:'/demo/test',state:{name:'tom',age:18}}}>详悄</Link>

注册路由(无需声明,正常注册即可):<Route path="/demo/test"component={Test}/>

获取state参数

import React from 'react'
import {useLocation} from 'react-router-dom'

export default function Detail() {
	const {state} = useLocation()
	console.log('@',x)
  // x就是location对象: 
	/*
		{
      hash: "",
      key: "ah9nv6sz",
      pathname: "/login",
      search: "?name=tom&age=18",
      state: {name: 'tom', age: 18}
    }
	*/
	return (
		<ul>
			<li>名字:{state.name}</li>
			<li>年龄:{state.age}</li>
		</ul>
	)
}

网站公告

今日签到

点亮在社区的每一天
去签到