react-router-dom中的模糊匹配原理
阿新 • • 發佈:2019-01-28
原理解析:
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} fromconst 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
{/* 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"
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