一、知识内容
与 v5 对比:
- 所有路由配置都在一个根组件内编写,子组件路由在路由标签插槽里写,不在去子组件内单独配置;
import React from 'react'
import { HashRouter, Navigate, NavLink, Route, Routes } from 'react-router-dom'
import A from './router-demo/A'
import B from './router-demo/B'
import C from './router-demo/C'
import D from './router-demo/D'
const App = () => {
return (
<HashRouter>
<NavLink to="/a">a组件</NavLink>
<NavLink to="/b">b组件</NavLink>
<NavLink to="/c">c组件</NavLink>
<Routes>
<Route path="/" element={<Navigate to="/a" />}></Route>
<Route path="/a" element={<A />}>
<Route path="/a/d" element={<D />}></Route>
</Route>
<Route path="/b" element={<B />}></Route>
<Route path="/c/id?/name?" element={<C />}></Route>
<Route path="*" element={<Navigate to="/a" />}></Route>
</Routes>
</HashRouter>
)
}
export default App
- 路由传参:没变,还是query方式、params路径拼接方式、隐式
state
传参(刷新还在); - 路由跳转:
Link\NavLink
标签to
属性、hooks函数useNavigate
,没有useHistory
- 路由对象:只能通过hooks函数获取,有
useLocation
和useSearchParams、useParam
import React from 'react'
import { NavLink, Outlet, useNavigate } from 'react-router-dom'
const A = () => {
const navigate = useNavigate()
const handle = () => {
// 1、query方式
navigate('/c?id=666', { replace: true })
// 2、路径拼接方式
// navigate('/c/66/aa')
// 3、隐式传参,state位置移到外层了
navigate('/c?id=666', { state: {id:123} })
// navigate(
// {
// pathname: '/c',
// search: 'id=66',
// },
// { replace: false }
// )
}
return (
<div>
<NavLink to="/a/d?id=66">前往d组件</NavLink>
<div onClick={handle}>通过hooks跳转</div>
<Outlet></Outlet>
</div>
)
}
export default A
- 获取路径参数
import React from 'react'
import { useLocation, useParams, useSearchParams } from 'react-router-dom'
const C = () => {
// 1、获取query方式参数:/c?id=66
const location = useLocation()
console.log(location.search) //'?id=66'
// let usp = new URLSearchParams(location.search)
let [usp] = useSearchParams()
console.log(usp.get('id'))//66
// 2、获取路径拼接参数:/c/66/aa
let params = useParams()
console.log(params)//{id: '66', name: 'aa'}
// 3、获取隐式传参
let location = useLocation()
console.log(location.state) //{id: '66'}
return <div>c组件</div>
}
export default C