在react-router中組件里面的跳轉(zhuǎn)可以用<Link>
但是在組件外面改如何跳轉(zhuǎn),需要用到react路由的history
replace方法和push方法使用形式一樣,replace的作用是取代當(dāng)前歷史記錄
go,此方法用來前進(jìn)或者倒退,history.go(-1);
goBack,此方法用來回退,history.goBack();
goForward,此方法用來前進(jìn),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可以傳參
獲取參數(shù):
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 ;} } |
如果不調(diào)用history.go則路由改變了,但是頁(yè)面不會(huì)跳轉(zhuǎn)。
到此這篇關(guān)于React Router 如何使用history跳轉(zhuǎn)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)React Router history跳轉(zhuǎn)內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_34153210/article/details/106233970