我是靠谱客的博主 飞快水蜜桃,这篇文章主要介绍React Router 如何使用history跳转的实现,现在分享给大家,希望可以做个参考。

在react-router中组件里面的跳转可以用<Link>

但是在组件外面改如何跳转,需要用到react路由的history

replace方法和push方法使用形式一样,replace的作用是取代当前历史记录
go,此方法用来前进或者倒退,history.go(-1);
goBack,此方法用来回退,history.goBack();
goForward,此方法用来前进,history.goForward();

1.hook

复制代码
1
2
3
4
5
6
7
import {useHistory} from 'react-router-dom'; function goPage(e) { history.push({ pathname: "/home", state: {id: 1} }); }

pathname是路由地址,state可以传参

获取参数:

复制代码
1
2
3
4
5
import {useLocation} from 'react-router-dom'; function getParams(){ let location = useLocation(); let id = location.state.id; }

2.class组件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React from 'react'; import {createBrowserHistory} from "history"; class App extends React.Component{ constructor(props) { super(props); } goPage() { let history = createBrowserHistory() history.push({ pathname: "/home", state: {id: 1} }); history.go(); } render() {return null;} }

如果不调用history.go则路由改变了,但是页面不会跳转。

到此这篇关于React Router 如何使用history跳转的实现的文章就介绍到这了,更多相关React Router history跳转内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是飞快水蜜桃最近收集整理的关于React Router 如何使用history跳转的实现的全部内容,更多相关React内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(178)

评论列表共有 0 条评论

立即
投稿
返回
顶部