React Router 5.1.0使用useHistory做页面跳转导航

从React Router v5.1.0开始,新增了useHistory钩子(hook),如果是使用React >16.8.0,编写以下函数组件,使用useHistory即可实现编程时页面跳转导航。

示例:

import { useHistory } from "react-router-dom";
function HomeButton() {
  const history = useHistory();
  function handleClick() {
    history.push("/home");
  }
  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

 

React Router v4编程式页面跳转的方式(补充)

如果是React Router v4,可以使用以下方法:

  • 使用withRouter组件
  • 使用<Route>标签
  • 使用context

1、使用withRouter组件

withRouter组件将注入history对象作为该组件的属性。这样,不需要处理context,可直接访问push和replace方法。

示例:

import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

2、使用<Route>标签

<Route>组件不仅用于匹配位置。 您可以渲染无路径的路由,它始终与当前位置匹配。 <Route>组件传递与withRouter相同的属性,因此能够通过history的属性访问history的方法。

import { Route } from 'react-router-dom'
const Button = () => (
  <Route render={({ history}) => (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </button>
  )} />
)

3、使用context

这个方法不推荐,context api不是很稳定。示例如下:

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      context.history.push('/new-location')
    }}
  >
    Click Me!
  </button>
)

Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}

推荐使用方法1和2,实现起来也简单。

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值