React Router history跳转 React Router 怎样使用history跳转的实现

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React Router history跳转 React Router 怎样使用history跳转的实现

香辣素毛肚   2021-04-06 我要评论
想了解React Router 怎样使用history跳转的实现的相关内容吗,香辣素毛肚在本文为您仔细讲解React Router history跳转的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:React,Router,history跳转,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则路由改变了,但是页面不会跳转。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们