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

原理解析:

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

猜你喜欢

转载自blog.csdn.net/itzhongzi/article/details/79094239
今日推荐