React Router 如何使用history跳转的实现

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React Router 如何使用history跳转的实现脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

在react-router中组件里面的跳转可以用<Link>

但是在组件外面改如何跳转,需要用到react路由的history

replace方法和push方法使用形式一样,replace的作用是取代当前历史记录
go,此方法用来前进或者倒退,history.go(-1);
goBack,此方法用来回退,history.goBack();
goForward,此方法用来前进,history.goForward();

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则路由改变了,但是页面不会跳转。

到此这篇关于React Router 如何使用history跳转的实现的文章就介绍到这了,更多相关React Router history跳转内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的React Router 如何使用history跳转的实现全部内容,希望文章能够帮你解决React Router 如何使用history跳转的实现所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:React