1. 程式人生 > >react-router-dom中的模糊匹配原理

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