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