React router之hooks

Hooks

React router 为您提供了一些 hook,方便你在组件中随时取用 react-router 的状态和进行导航操作

注意:你必须使用 react@16.8+ 才能使用这些 hooks!

且下面是在函数式组件中使用的方法,类式组件对应的是:

this.props.history

this.props.location

this.props.match.params

  • useHistory
  • useLocation
  • useParams
  • useRouteMatch

useHistory

useHistory 钩子返回 history 对象,你可以在上面进行导航等操作

import { useHistory } from 'react-router-dom'

function HomeButton() {
  let history = useHistory()

  function handleClick() {
    history.push('/home')
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  )
}

useLocation

useLocation 钩子返回一个代表当前 url 的 location 对象。你可以把它想象为一个 useState 钩子,并且在每次 url 变化后会替换为一个新对象。

mport React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Switch, useLocation } from 'react-router-dom'

function usePageViews() {
  let location = useLocation()
  React.useEffect(() => {
    ga.send(['pageview', location.pathname])
  }, [location])
}

function App() {
  usePageViews()
  return <Switch>...</Switch>
}

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  node
)

useParams

useLocation 钩子返回一个代表当前 url 的 location 对象。你可以把它想象为一个 useState 钩子,并且在每次 url 变化后会替换为一个新对象。

import React from 'react'
import ReactDOM from 'react-dom'
import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from 'react-router-dom'

function BlogPost() {
  let { slug } = useParams()
  return <div>Now showing post {slug}</div>
}

ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/">
        <HomePage />
      </Route>
      <Route path="/blog/:slug">
        <BlogPost />
      </Route>
    </Switch>
  </Router>,
  node
)

useRouteMatch

useRouteMatch 钩子会尝试以与``组件相同的方式去匹配当前 url。在你希望获得路径匹配数据但不希望使用Route的时候他可能会很有用

之前:

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

function BlogPost() {
  return (
    <Route
      path="/blog/:slug"
      render={({ match }) => {
        // Do whatever you want with the match...
        return <div />
      }}
    />
  )
}

现在:

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

function BlogPost() {
  let match = useRouteMatch('/blog/:slug')

  // Do whatever you want with the match...
  return <div />
}

useRouteMatch 钩子接受一个可选参数,该参数与 matchPath 的 props 参数相同。它可以是字符串的路径名(如上面的示例),也可以是带有 Route接受的 match 属性对象,如下所示:

const match = useRouteMatch({
  path: '/BLOG/:slug/',
  strict: true,
  sensitive: true
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值