
学一个React开发tips:React Router里使用history跳转。
在react-router中组件里面的跳转可以用<link>
但是在组件外面改如何跳转,需要用到React路由的history
Replace方法和push方法使用形式一样,replace的作用是取代当前历史记录
go,此方法用来前进或者倒退,history.go(-1);
goBack,此方法用来回退,history.goBack();
goForward,此方法用来前进,history.goForward();
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;
}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则路由改变了,但是页面不会跳转。




网友评论文明上网理性发言 已有0人参与
发表评论: