为什么需要reactRouter
react是单页面的spa,如果想要实现页面的跳转就得借助reaact-router。
router可以在同一个页面的情况下通过切换组件去切换页面的展示,不会进行页面的刷新
依赖包
react
react-router-dom 用于web,使用BrouserRouter(pushstate、popstate);使用hashRouter(wndow。location.hash、hashChange)
react-router-native
react-router-config 实现router的管理
简单使用
关键点
1、导入 import {BrowserRouter as router, Route, Link, Switch} from 'react-router-dom';
2、使用 router包裹需导航的组件
3、使用 link to='path'
4、使用route进行导航规则的设置
export const App: React.FC => {
return (
<Router>
<Link to='/'>home组件</Link>
<Link to='/register'>register组件</Link>
<Link to='/landing'>landing组件</Link>
<route path='/' exact component={Home}>
<route path='/register' component={Register}>
<route path='/landing' component=Landing}>
</Router>
)
}
export const App: React.FC => {
const name = 'valid'
return (
<Router>
<>
<Page>
<Link to='/'>home组件</Link>
<Link to=`/register/{name}`>register组件</Link>
<Link to='/landing'>landing组件</Link>
</Page>
<Swicth>
<Route path='/' exact component={Home}>
<Route path='/register/:name' component={Register}>
<Route path='/landing' component={Landing}>
</Switch>
</>
</Router>
)
}
通过`Route`作为顶层组件包裹其他组件后,页面组件就可以接收到一些路由相关的东西,比如`props.history`
路由守卫
作用:在某些情况下才能够进行页面的跳转,比如用户必须登录后才能进入用户信息主页
使用:通过某些值的判断,来渲染对应的展示页
isAuthorized ?<> <Route path='/register/:name' component={Register}></> : <Redirect to='/'/>
react-router-hooks
import { useHistory } from 'react-router-dom'
const history = useHistory()
history.goFoward()
history.goBack()
history.push()
history.replace()
import { useParams } from 'react-router-dom'
const { name } = useParams()
import { useLocation } from 'react-router-dom'
const { url } = useLocation()