项目创建和路由的引入
项目创建
create-react-app routerdemo
路由引入
npm i react-router-dom@6
基础功能方法的封装
重定向使用Navigate
import React from 'react'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
export default function Redirect(props) {
const { to } = props
const navigate = useNavigate()
useEffect(()=>{
navigate(to,{replace:true})
})
return null
}
路由拦截
import React from 'react'
import Redirect from './Redirect'
export default function AuthComponent(props) {
// 插槽
return localStorage.getItem('token')?
props.children:<Redirect to="/login"></Redirect>
}
懒加载
import React from 'react'
// 懒加载作用:按需加载
function LazyLoad({path}) {
const Component=React.lazy(()=>import(path))
return (
<React.Suspense fallback={<>Loding...</>}>
<Component></Component>
</React.Suspense>
)
}
export default LazyLoad
配置路由
全局配置路由
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
useRoutes钩子配置路由
import React from 'react'
import { useRoutes } from 'react-router-dom'
import LazyLoad from '../component/LazyLoad'
import Redirect from '../component/Redirect'
import AuthComponent from '../component/AuthComponent'
export default function ComStemRouter() {
const element = useRoutes([
{
path: '/home', element:<AuthComponent> {LazyLoad({ path: "Home" })}</AuthComponent>, children: [
{
path: 'index', element: LazyLoad({ path: 'index/Index' })
},
{
path: 'feed', element: LazyLoad({ path: 'feed/Feed' })
},
{
path: 'mine', element: LazyLoad({ path: 'mine/Mine' })
},
{
path: '', element: <Redirect to="/home/index"></Redirect>
}
]
},
{
path: '/detail', element: LazyLoad({ path: "feed/FeedDetail" })
},
{
path: '/login', element: LazyLoad({ path: "Login" })
},
{
path: '/', element: <Redirect to="/home"></Redirect>
},
{
path: '*', element: <div>404</div>
}
])
return element
}
声明式导航和底部导航
import React from 'react'
import { NavLink } from 'react-router-dom'
// 底部导航和声明式导航
export default function HomeToobar() {
const list = [{name:"首页",path:'index'},{name:"动态",path:'feed'},{name:"我的",path:'mine'}]
return (
<ul className='toobar'>
{list.map(item=><li key={item.name}>
{/* 声明式导航 可以自定义class,默认active*/}
<NavLink to={item.path} className={({isActive})=>isActive?"zidingyi":''}>{item.name}</NavLink>
</li>)}
</ul>
)
}
编程式导航和传参
//url传参
const navigate = useNavigate()
navigate(`/detail?id=${id}`)
//获取url参数
import { useSearchParams } from 'react-router-dom'
const [searchParams, setSearchParams] = useSearchParams()
// 获取参数
searchParams.get('id')
// 判断参数是否存在
searchParams.has('id')
// 同时页面内也可以用set方法来改变路由
setSearchParams({"id":2})