Reate中路由的使用

路由安装

  1. win+r进入命令窗口,输入cmd
  2. cd到文件路径下
  3. 输入下面代码
npm i react-router-dom@5.0

路由组件

导入

import{HashRouter as Router,Route,NavLink,Redirect,Switch} from 'react-router-dom'

内容

HashRouter哈希路由 as起别名 router路由

BrowserRouter 浏览器路由 as Router

Route 存放路由的页面:path 路径,component组件,render渲染

<Route path="/" component={Home} exact></Route>

NavLink 导航链接:to为链接地址,exac为t精确匹配,匹配的链接会自动添加class active

<NavLink to="/" exact>首页</NavLink>

Redirect 重定向:例如需要登录后才能进入个人中心,点击用户中心就自动跳转到登录页面,这就是重定向。from表示从哪个路径,to表示定向到的路径。

<Redirect from='/admin' to="/admin/dash"></Redirect>

Switch 一次只匹配一个路由:例如404状态页,未使用Switch时无论是哪个页面都会显示,使用后,在Switch内的路径路径页面中就不会显示,在其他页面才会显示

          <Switch>
            <Route path="/" component={Home} exact></Route>
            <Route path="/about" component={About}></Route>
            <Route path="/details/:id" component={Details}></Route>
            <Private path="/admin">
                <Admin></Admin>
            </Private>
            <Route path="/admin" component={Admin}></Route>
            <Route path="/login" component={Login}></Route>
            {/* * 匹配任意路径 */}
            <Route path="*" component={NoMatch}></Route>

         </Switch>

路由props

match匹配的路由参数

  1. path路径
  2. url地址
  3. isExact 精确匹配
  4. params参数

history历史记录

go跳转

<button onClick={()=>history.go('/')}>首页</button>

goBack返回

<button onClick={()=>history.goBack('/')}>首页</button>

goForward 前进

<button onClick={()=>history.go('/')}>首页</button>

push插入

是在当前页面插入一个页面,点击后再返回可以回到点击按钮前一个页面

<button onClick={()=>history.goForward ('/')}>首页</button>

replace替换

是替换当前页面,点击后再返回可以回到点击按钮前第一个页面

<button onClick={()=>history.replace('/')}>首页</button>

listen监听

location

  1. pathname路径地址
  2. search查询
  3. hash哈希
  4. state状态
        <NavLink to={{
          pathname:"/details/abc",
          search:"name=mumu&age=18",
          hash:"good",
          state:{reidrect:"/about"}
        }}>详情abc</NavLink>

普通路由

<NavLink to=“/about”>
<Route path="/about" component={About}>

路由传参

<NavLink to=“/details/abc”>
<Route path="/details/:id" component={Details}>

获取参数

props.match.params.id

子路由

父路由Admin和普通是一样的

<NavLink to="/admin/dash">
<Route path="/admin/dash" component={Dash}>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值