在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跳轉內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_34153210/article/details/106233970