react学习笔记之react-router4.x中JS路由跳转

react学习笔记之react-router4.x中JS路由跳转

admin
2018-12-15 / 0 评论 / 928 阅读 / 正在检测是否收录...

在react开发单页应用的时候,有时我们需要通过js触发路由的跳转而不是紧紧通过Link组件链接跳转。如:登录成功自动跳转到网站首页或者redirect页;在ajax请求中,通过公共方法验证登录token是否有效,如果无效跳转到登录页等等。

针对上面的两种情况,就有两种路由跳转场景,第一种:在中间中触发路由跳转,第二种:在非Component组件的js中触发路由跳转,这两种场景的跳转方法分别为:

一,组件中跳转到另一个路由组件:

  • 从react-router-dom中导入withRouter方法

    import { withRouter } from 'react-router-dom';
  • 使用withRouter方法加工需要触发路由跳转的组件

    export default withRouter(Login);
  • 通过withRouter加工后的组件会多出一个history props,这时就可以通过history的push方法跳转路由了。

    this.props.history.push('/home');

二,非组件JS函数中触发路由跳转

  • 从history中导入createHashHistory方法(如果您的react应用使用的是history路由则导入createBrowserHistory)

    import { createHashHistory } from 'history'; // 如果是hash路由
    import { createBrowserHistory } from 'history'; // 如果是history路由
    React-Router v4.0上已经不推荐使用hashRouter,主推browserRouter,但是因为使用browserRouter需要服务端配合可能造成不便,有时还是需要用到hashRouter。
  • 创建history实例

    const history = createHashHistory();
  • 跳转路由

    history.push('/login');
0

评论 (0)

取消