reactRouter学习

138 阅读1分钟

为什么需要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, RouteLink, Switch} from 'react-router-dom';
2、使用 router包裹需导航的组件
3、使用 link to='path'
4、使用route进行导航规则的设置
//exact 表示精确匹配
//swicth 表示只会匹配其中一个
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`
//路由跳转 、重定向
//关键词: history.goFoward goBack push replace(会将之前页面销毁)
//重定向 组件<Redirect to='path'>(会将之前页面销毁)
路由守卫
作用:在某些情况下才能够进行页面的跳转,比如用户必须登录后才能进入用户信息主页
使用:通过某些值的判断,来渲染对应的展示页
isAuthorized ?<> <Route path='/register/:name' component={Register}></> : <Redirect to='/'/>

react-router-hooks

//useHistory
import { useHistory } from 'react-router-dom'
//使用route包裹的组件都可以通过该方式取出history
const history = useHistory()
history.goFoward()
history.goBack()
history.push()
history.replace()
//useParams
import { useParams } from 'react-router-dom'
//使用该方式可以拿到动态路由上的数据
const { name } = useParams()
//useLoaction
import { useLocation } from 'react-router-dom'
//使用该hooks可以拿到当前URL 的 location 对象
const { url } = useLocation()