react-router-dom中的模糊匹配原理

本文介绍如何使用React Router解决路由模糊匹配问题,通过Switch组件确保仅渲染首个匹配的路径,避免静态路径被动态路径覆盖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理解析:

1、将可能匹配不到的Route 的path属性写成动态的  path="/:id"  

2、并且将所有的Route用Switch标签包裹。(switch包裹的Route只会渲染首次匹配到的 组件。react-router-dom中默认是渲染所有匹配到的组件的)

3、给动态路由添加一个 公共的未匹配到路径的组件,并在  该组件中  使用 路由的属性   match.params.id 获取 传入的动态 id


核心代码:

import React from 'react'
import {
BrowserRouter as Router,
Route,
Link,
Switch
} from 'react-router-dom'

const AmbiguousExample = () => (
<Router>
<div>
<ul>
<li><Link to="/about">About Us (static)</Link></li>
<li><Link to="/company">Company (static)</Link></li>
<li><Link to="/kim">Kim (dynamic)</Link></li>
<li><Link to="/chris">Chris (dynamic)</Link></li>
</ul>

{/*
Sometimes you want to have a whitelist of static paths
like "/about" and "/company" but also allow for dynamic
patterns like "/:user". The problem is that "/about"
is ambiguous and will match both "/about" and "/:user".
Most routers have an algorithm to decide for you what
it will match since they only allow you to match one
"route". React Router lets you match in multiple places
on purpose (sidebars, breadcrumbs, etc). So, when you
want to clear up any ambiguous matching, and not match
"/about" to "/:user", just wrap your <Route>s in a
<Switch>. It will render the first one that matches.
*/}
<Switch>
<Route path="/about" component={About}/>
<Route path="/company" component={Company}/>
<Route path="/:id" component={User}/>
</Switch>
</div>
</Router>
)

const About = () => <h2>About</h2>
const Company = () => <h2>Company</h2>
const User = ({ match }) => {

console.log(match)
return (
<div>
<h2>User:{match.params.id}</h2>
</div>
)
}

export default AmbiguousExample

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITzhongzi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值