一、React路由介绍
- 前端路由的功能:让用户从一个视图导航到另一个视图
- 前端路由是一套映射规则,在React中,是URL路径和组件的对应关系
- 使用React路由简单来说,就是配置路径和组件(配对)
二、路由的基本使用
1、使用步骤
1、安装
yarn add react-router-dom
2、导入路由的三个核心组件:Router/Route/Link
import {BrowserRouter as Router, Route, Link} from "react-router-dom"
3、使用Router组件 包裹整个应用
import {BrowserRouter as Router, Route, Link} from "react-router-dom"
const First = () => <p> 页面一的内容 </p>
const App = () => {
<Router>
<div>
<h1>React路由基础</h1>
{/* 指定路由入口 */}
<link to="/first">页面一</link>
{/* 指定路由出口 */}
<Route path="first" component={First} />
</div>
</Router>
}
4、常用组件说明
- Router组件:包裹整个应用,一个React应用只需要使用一次
- 俩种常用Router:HashRouter和BrowserRouter
- HashRouter:使用URL的哈希值实现
- BrowserRouter:使用H5的historyAPI实现
三、路由的执行过程
- 点击Link组件(a标签),修改了地址栏中的url
- React 路由监听到地址栏url的变化
- React路由内部遍历所有的Route组件,使用路由规则(path)与pathname(浏览器中的地址栏)进行匹配
- 当路由规则(path) 能够匹配地址栏中的pathname时,就展示该Route组件的内容
四、编程式导航
- 编程式导航:通过JS代码来实现页面跳转
- history是React路由提供的,用于获取浏览器历史记录的相关信息
import {BrowserRouter as Router, Route, Link} from "react-router-dom"
const Home = () => <p> 页面一的内容 </p>
class Login extends React.Component {
const loginHandle = ()=>{
this.props.history.push('/home')
}
render() {
return (
<div>
<p>登录页面:</p>
<button onClick={this.handleLogin}></button>
</div>
)
}
}
const Login = (props) => {
const loginHandle = ()=>{
props.history.push('/home')
}
render() {
return (
<div>
<p>登录页面:</p>
<button onClick={this.handleLogin}></button>
</div>
)
}
}
const App = () => {
<Router>
<div>
<h1>React路由基础</h1>
<Login></Login>
<Route path="Home" component={First} />
</div>
</Router>
}
ReactDOM.render(<App />,document.getElementByID('root'))
五、默认路由
<Route path="/" component={Home} />
六、模糊匹配模式
- 问题:当Link组件的to属性值为
/login 时,为什么默认路由也被匹配成功?
- 默认情况下,React路由时模糊匹配模式
- 模糊匹配规则:只要pathname以path开头就会匹配成功
<Link to="/login">登录页面</Link>
<Route path="/" component={Home}/>
七、精确匹配模式
- 给Route组件添加exact属性,让其变为精确匹配模式
<Route exact path="/" component=... />
八、路由传参
1. 动态参数
创建
<Router>
<div className="App">
{/* 房源详情的路由规则: */}
<Route path="/detail/:id" component={HouseDetail} />
</div>
</Router>
使用
this.props.history.push('/detail/1')
const { id } = this.props.match.params
2. state传参:
创建
<Router>
<Route path="/rent/add" component={RentAdd} />
</Router>
使用
// 函数值传数据
this.props.history.replace('/rent/add', {
name: item.communityName,
id: item.community
})
// 路由链接传数据
<Link to={
{
pathname:'home/message/list',
state:{
name: item.communityName,
id: item.community
}
}
>
{ msgObj.title }
</ Link>
// 接收数据
const { state } = props.location
if (state) {
community.name = state.name
community.id = state.id
}
3. search传参
创建
<Routes><Route path='list' element={<List/>} /></Routes>
使用
// 路由链接传参
<Link to={`/list/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link>
// 编程路由传参
this.props.history.push(`/list/?id=${id}&title=${title}`)
// 接收参数
// 获取到的search是urlencoded编码字符串,需要借助querystring解析
import {qs} from 'querystring' //引入
const {search} = this.props.location;
const {id,title} = qs.parse(search.slice(1)); //截取