React-Route中新增的部分Hooks

useLocation

可以用来查看当前的路由,当需要匹配路由进行跳转的时候使用。

使用方式如下:

import {useLocation} from "react-router-dom";

const {pathname} = useLocation

const pathList = pathname.split('/').filter((str) => str.length > 0);

console.log("pathList", pathList);

...

我们可以看一下useLocation获得的log结果:

 

 还有另外一种方式,不需要使用Hooks:

const {pathname} = window.location;

const pathList = pathname.split("/").filter((str) => str.length > 0);

useRouteMatch

这个Hooks可以在不使用<Route>的情况下,来实现与<Route>相同功能的路由匹配。

// before
import { Route } from 'react-router-dom'

const A = () => {
  return (
    <div>
      <Route
        path="/a1"
        render={({ url }) => {
          return url ? <Child match={url} /> : <Error />
        }}
      />
    </div>
  )
}

// after
import { useRouteMatch } from 'react-router-dom'

const A = () => {
  let url = useRouteMatch({
    path: '/a1',
  })

  return (
    <div>
      {url ? <Child match={url} /> : <Error />}
    </div>
  )
}

useHistory

这个Hooks可以用来进行路由匹配的跳转:

import {useHistory} from "react-router-dom";

const history = useHistory();

history.push(`/a1/b1`);

...

还有很多的功能,比如:

`history.goBack()`------返回上一个网页

`history.listen()`-------location发生改变的时候触发的回掉

......

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值