React路由跳转的几种方式

目录

React路由跳转的几种方式

1. params形式,路由跳转后,参数会显示在地址栏

 2. 使用state的形式,页面刷新不会丢失数据,并且地址栏也看不到数据


React路由跳转的几种方式

注意: 这里使用的react-router-dom是版本5以上,路由形式是history模式
react-router-dom文档地址,其中依赖包history的github地址

1. params形式,路由跳转后,参数会显示在地址栏

React路由跳转的几种方式

        跳转的方法是使用history.push({pathname: '/personal', search: 'test=22222'}),其中search键对应的值就是拼接在地址栏的数据

import React from 'react'
import { useHistory } from 'react-router-dom'
export default ()=> {
	const history = useHistory()
	// 页面跳转方法
	history.push({pathname: '/personal', search: 'test=22222'})
	return 123
}

        接收的方法。数据都是存储在useLocation中的search获取

import React from 'react'
import { useLocation } from 'react-router-dom'
export default ()=> {
	const location = useLocation()
	// 页面跳转方法
	console.log(location, 'props')
	return 123
}

React路由跳转的几种方式

 2. 使用state的形式,页面刷新不会丢失数据,并且地址栏也看不到数据

     跳转的方法是使用history.push({pathname: '/personal', state: {test: 'dashboard'}}),其中search键对应的值就是拼接在地址栏的数据

import React from 'react'
import { useHistory } from 'react-router-dom'
export default ()=> {
	const history = useHistory()
	// 页面跳转方法
	history.push({pathname: '/personal', state: { test: 'dashboard' }})
	return 123
}

        接收的方法。数据都是存储在useLocation中的search获取

import React from 'react'
import { useLocation } from 'react-router-dom'
export default ()=> {
	const location = useLocation()
	// 页面跳转方法
	console.log(location, 'props')
	return 123
}

React路由跳转的几种方式

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。