1、http://127.0.0.1:8080/#/b?name=tom&age=10
路由:<Route path='/b' element={<B />}></Route>
A组件中:navigate('/b?name=tom&age=10')
==> 浏览器地址栏:http://127.0.0.1:8080/#/b?name=tom&age=10
(‘/b?name=tom&age=10’ 可换成{pathname: '/b',search: '?name=tom&age=10' }
)
B组件中:
const [searchParams, _] = useSearchParams()
const obj = {}
for (let item of searchParams.entries()) {
obj[item[0]] = item[1]
}
// obj==> {name: 'tom', age: '10'}
2、http://127.0.0.1:8080/#/b/tom/10
路由: <Route path='/b/:name?/:age?' element={<B />}></Route>
A组件中:navigate('/b/tom/10')
==> 浏览器地址栏:http://127.0.0.1:8080/#/b/tom/10
B组件中:
const params=useParams() // params ==> {name: 'tom', age: '10'}
3、隐式传参 http://127.0.0.1:8080/#/b
A组件中:
navigate('/b', {
replace: true,
state: {
name: 'jerry',
age: 9
}
})
==> 浏览器地址栏:http://127.0.0.1:8080/#/b/
B组件中:
const location = useLocation()
console.log(location.state) //{name: 'jerry', age: 9}