前言
useMatch
是 React Router
中的一個鉤子,用于判斷當前 URL
路徑是否與指定模式匹配,并返回匹配的詳細信息。
它常用于動態路由參數提取、條件渲染和導航高亮等場景。
一、useMatch 核心功能
路徑匹配檢測:判斷當前路徑是否符合指定模式
參數提取:從動態路由中獲取參數值(如 /users/:id
)
精準匹配控制:支持路徑的精確匹配和模糊匹配
二、useMatch 基本用法
import { useMatch } from "react-router-dom";function UserProfile() {const match = useMatch("/users/:userId");if (!match) return <div>未找到用戶</div>;return <div>用戶ID: {match.params.userId}</div>;
}// 當訪問 /users/123 時顯示: 用戶ID: 123
三、useMatch 參數說明
const match = useMatch(pattern: string | PathPattern);
3.1、pattern
參數:
字符串格式:支持動態參數(:param
)和通配符(*)
3.2、 對象格式(PathPattern
):
{path: string; // 路徑模式caseSensitive?: boolean; // 是否區分大小寫end?: boolean; // 是否要求完全匹配
}
3.3、 返回值結構
params
:類型{object},返回的動態路由參數鍵值對
pathname
:類型{string}, 匹配的實際路徑
pattern :
類型{object}, 使用的匹配模式配置
四、useMatch完整代碼案例
4.1、導航菜單高亮
function NavBar() {const homeMatch = useMatch("/");const aboutMatch = useMatch("/about");return (<nav><Link to="/" className={homeMatch ? "active" : ""}>首頁</Link><Link to="/about" className={aboutMatch ? "active" : ""}>關于我們</Link></nav>);
}
4.2、動態面包屑導航
function Breadcrumbs() {const projectMatch = useMatch("/projects/:projectId");const taskMatch = useMatch("/projects/:projectId/tasks/:taskId");return (<div className="breadcrumbs">{projectMatch && (<span>{projectMatch.params.projectId}</span>)}{taskMatch && (<span> / {taskMatch.params.taskId}</span>)}</div>);
}
五、useMatch 高級用法
5.1. 精確匹配控制
// 僅當路徑完全匹配 /about 時返回非null
const exactMatch = useMatch({path: "/about",end: true
});// 匹配 /about 及其子路徑(如 /about/team)
const fuzzyMatch = useMatch({path: "/about",end: false
});
5.2、 多級動態參數
function ProductPage() {const match = useMatch("/category/:categoryId/product/:productId");return (<div>分類ID: {match?.params.categoryId}商品ID: {match?.params.productId}</div>);
}// 訪問 /category/electronics/product/123 時顯示:
// 分類ID: electronics 商品ID: 123
六、useMatch 與useParams 的對比
七、useMatch 使用注意事項
7.1、路由上下文要求
組件必須位于 <Router>
上下文環境中
7.2、路徑匹配優先級
在嵌套路由中,父路由的匹配優先級高于子路由
7.3、性能優化
避免在高頻渲染的組件中使用,必要時可配合 useMemo
:
const match = useMatch("/products");
const shouldHighlight = useMemo(() => !!match, [match]);
7.4、大小寫敏感配置
默認不區分路徑大小寫,可通過配置開啟:
useMatch({path: "/AboutUs",caseSensitive: true
});
八、useMatch 典型錯誤處理
錯誤:未處理 null 情況
// ? 錯誤:當路徑不匹配時 params 為 undefined
function UserPage() {const { userId } = useMatch("/users/:userId").params;return <div>{userId}</div>;
}// ? 正確:安全訪問
function UserPage() {const match = useMatch("/users/:userId");return match ? <div>{match.params.userId}</div> : null;
}
九、useMatch 最佳實踐
9.1、創建可復用的匹配鉤子
function useIsActive(path: string) {const match = useMatch(path);return !!match;
}// 使用示例
const isProductsActive = useIsActive("/products");
9.2、組合其他路由鉤子
function SmartLink({ to, children }) {const match = useMatch(to);const navigate = useNavigate();return (<button onClick={() => navigate(to)}style={{ fontWeight: match ? "bold" : "normal" }}>{children}</button>);
}
總結
使用 useMatch,我們可以精確控制路徑匹配邏輯,實現靈活的路由驅動型UI交互。
這是構建動態導航系統、權限控制模塊和上下文敏感組件的關鍵工具。