React Router 如何使用history跳轉

1.hook

import {useHistory} from 'react-router-dom';
function goPage(e) {
	history.push({
		pathname: "/home",
		state: {id: 1}
		});
}

pathname是路由地址,state可以傳參

獲取參數:

import {useLocation} from 'react-router-dom';
function getParams(){
let location = useLocation();
let id = location.state.id;
}

2.class組件

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則路由改變了,但是頁面不會跳轉。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章