现代的前端应用大多数是SPA(单页应用程序),也就是只有一个HTML页面的应用程序。因为它的用户体验更好、对服务器压力更小,所以更受欢迎。为了有效的使用单个页面来管理多页面的功能,前端路由应运而生。
安装: yarn add react-router-dom
导入路由的三个核心组件: Router / Route / Link
import {BrowserRouter as Router, Route, Link} from 'react-router-dom'
// ... 省略页面内容
页面一
// const First = () => 页面一的内容
function First() {return (页面一的内容
)
}// 使用Router组件包裹整个应用
const App = () => (React路由基础
{/* 指定路由入口 */}页面一{/* 指定路由出口 */} } />
)
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
// import { HashRouter as Router, Route, Link } from 'react-router-dom'
用于指定导航链接(a 标签)
// to属性:浏览器地址栏中的pathname(location.pathname)
页面一
指定路由展示组件相关信息
// path属性:路由规则
// component属性:展示的组件
// Route组件写在哪,渲染出来的组件就展示在哪
{/* 指定路由出口 */} } />
class Login extends Component {handleLogin = () => {// ...this.props.history.push('/home')}render() { }
}
编程式导航是使用路由组件 this.props.history 提供的 API 进行路由跳转:
this.props.history.push(path, state)
this.props.history.replace(path, state)
this.props.history.goForward()
this.props.history.goBack()
this.props.history.go(n)
// 编程式导航传参
this.props.history.push(`/home/message/detail/${id}/${title}`)
this.props.history.push(`/home/message/detail?id=${id}&title=${title}`)
this.props.history.push(`/home/message/detail`, { id: id, title: title })
withRouter 的作用:加工一般组件,让其拥有路由组件的 API ,如 this.props.history.push 等。
import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'class Header extends Component {...
}export default withRouter(Header)
useNavigate() 返回一个函数,调用该函数实现编程式路由导航。函数有两种参数传递方式。
可以使用navigate这个函数代替this.history.push、this.history.replace、this.history.gofoward、this.history.goback、this.history.go
第一种方式传递两个参数:路由和相关参数。参数只能设置 replace 和 state。想要传递 params 和 search 参数直接在路由带上。
第二种方式传递数字,代表前进或后退几步。
import { BrowserRouter as Router, Route, NavLink, Routes, useNavigate } from 'react-router-dom'