TanStack Router MatchRoute 组件:路由匹配条件渲染的完整指南与源码解析
TanStack Router MatchRoute 组件路由匹配条件渲染的完整指南与源码解析【免费下载链接】router A client-first, server-capable, fully type-safe router and full-stack framework for the web (React and more).项目地址: https://gitcode.com/GitHub_Trending/ro/routerMatchRoute是 TanStack Router 中useMatchRoutehook 的组件版本用于根据“某个路由是否匹配当前或 pending位置”这一结果来条件渲染子组件。本篇将完整覆盖MatchRoute的 props 契约to、params、search、fuzzy、pending等匹配选项以及children的两种形态、返回值规则与官方示例并深入 packages/react-router/src/Matches.tsx 的源码说明匹配订阅机制与useMatchRoute的实现原理帮助你在导航高亮、条件 UI、骨架屏等场景中正确使用该组件。一、MatchRoute 组件是什么MatchRoute组件接受与useMatchRoutehook 完全相同的匹配选项并额外提供用于条件渲染的 props。其官方定义见 MatchRoute 文档为A component version of theuseMatchRoutehook. It accepts the same options as theuseMatchRoutewith additional props to aid in conditional rendering.从源码 packages/react-router/src/Matches.tsx#L228-L243 可以看到MatchRoute的实现极其精炼——它内部调用useMatchRoute()得到匹配函数把组件 props 直接作为匹配选项传入再根据children的形态决定渲染策略export function MatchRoute TRouter extends AnyRouter RegisteredRouter, const TFrom extends string string, const TTo extends string | undefined undefined, // ... (props: MakeMatchRouteOptionsTRouter, TFrom, TTo, TMaskFrom, TMaskTo): any { const matchRoute useMatchRoute() const params matchRoute(props as any) as boolean if (typeof props.children function) { return (props.children as any)(params) } return params ? props.children : null }这段实现揭示了组件的三条核心规则匹配即订阅MatchRoute底层依赖useMatchRoute只要组件在渲染中使用它就会订阅路由位置变化匹配结果变化时自动重渲染children为 ReactNode 时匹配成功返回params为真值渲染children匹配失败返回null不渲染任何内容children为函数时无论匹配与否都会调用该函数并传入匹配到的 params 对象或false——组件本身始终渲染只根据匹配结果渲染不同内容。二、MatchRoute props 详解MatchRoute的 props 类型在源码中由 packages/react-router/src/Matches.tsx#L204-L219 的MakeMatchRouteOptions定义export type MakeMatchRouteOptions... UseMatchRouteOptions... { children?: | ((params?: ExpandResolveRouteTRouter, TFrom, TTo[types][allParams]) React.ReactNode) | React.ReactNode }它等于UseMatchRouteOptions即所有匹配选项见 UseMatchRouteOptionsType 文档加上childrenprop。...props匹配选项类型UseMatchRouteOptions即ToOptions MatchRouteOptions的组合包含to必填目标路由路径、params、search等导航选项以及下列匹配开关详见 MatchRouteOptionsType 文档选项类型说明tostring要匹配的路由路径支持$param占位符必填params对象参与匹配的已知路径参数省略的参数从当前位置解析search对象参与匹配的查询参数配合includeSearchpendingboolean为true时匹配 pending location导航中目标位置而非当前位置caseSensitiveboolean已废弃。大小写敏感性应改在路由定义或 router 全局选项caseSensitive中声明includeSearchboolean为true时用“深包含”方式匹配查询参数如{ a: 1 }可匹配{ a: 1, b: 2 }fuzzyboolean为true时做模糊匹配如/posts可匹配当前位置/posts/123其中fuzzy与pending是条件渲染场景最常用的两个开关官方文档给出了典型组合// 当前位置: /posts/123/foo/456 matchRoute({ to: /posts/$postId/foo/$fooId, params: { postId: 123 } }) // ^ { postId: 123, fooId: 456 } postId 显式给定fooId 自动解析 // 当前位置: /postspending 位置: /posts/123 matchRoute({ to: /posts/$postId, pending: true }) // ^ { postId: 123 }childrenprop可选两种形态React.ReactNode路由匹配成功时渲染的组件内容匹配失败时组件返回null。((params: TParams | false) React.ReactNode)无论是否匹配都会被调用的函数。参数为匹配到的路由 params 对象未匹配时收到false。官方文档指出这对“组件需要始终渲染、但要根据是否匹配渲染不同 props”的场景非常有用。源码中的分支逻辑与文档描述一一对应if (typeof props.children function) { return (props.children as any)(params) // params 为 params 对象或 false } return params ? props.children : null // 匹配则渲染否则 null注意函数形态下 params 是可选参数类型params?即匹配失败时可能收到false回调内应做!!match之类的真值判断。三、MatchRoute 返回值MatchRoute的返回值即childrenprop 本身或children函数的返回值——没有其他副作用它纯粹是一个“匹配驱动的条件渲染包装器”。四、完整示例官方文档给出的示例展示了函数形态children的典型用法无论是否匹配Spinner都会渲染只是show属性随匹配结果变化import { MatchRoute } from tanstack/react-router function Component() { return ( div MatchRoute to/posts/$postId params{{ postId: 123 }} pending {(match) Spinner show{!!match} waitdelay-50 /} /MatchRoute /div ) }要点拆解to/posts/$postIdparams{{ postId: 123 }}匹配postId为123的文章路由pending匹配的是导航中的目标位置适合在“即将到达”时提前显示加载态{(match) Spinner show{!!match} waitdelay-50 /}回调在每次位置变化后重新执行match为{ postId: 123 }或false。对应的 ReactNode 形态示例匹配才渲染MatchRoute to/posts/$postId params{{ postId: 123 }} PostDetailActions / /MatchRoute位置不匹配时该组件不渲染任何 DOM匹配后PostDetailActions出现在输出中无需手动管理布尔状态。五、源码纵深匹配如何订阅位置变化MatchRoute的全部能力来自 packages/react-router/src/Matches.tsx#L158-L202 中的useMatchRoute。其实现分为两条路径服务端路径SSRif (isServer ?? router.isServer) { return (opts) { const { pending, caseSensitive, fuzzy, includeSearch, ...rest } opts return router.matchRoute(rest as any, { pending, caseSensitive, fuzzy, includeSearch }) } }客户端路径用React.useCallback包裹同样的匹配逻辑但依赖列表中包含三个useSelector订阅[ router, useSelector(router.stores.location, (location) location.href), useSelector(router.stores.resolvedLocation, (location) location?.href), useSelector(router.stores.status), ]由此可以确认几个实现事实匹配的核心计算下沉到 router 实例hook 只是把opts拆分为“导航选项restto、params、search等”和“匹配开关pending、fuzzy、includeSearch、caseSensitive”再调用router.matchRoute(rest, { ... })订阅粒度是 href 与 status只有当location.href、resolvedLocation.href对应 pending/已解析位置或 routerstatus变化时useCallback才会生成新的匹配函数并触发组件重渲染。这正是pending选项能工作的前提——pending 位置对应resolvedLocationstore函数身份变化意味着重新渲染文档明确说明useMatchRoute返回的函数身份会随匹配所用的路由状态变化而改变因此适合“匹配结果决定渲染输出”的场景。与router.matchRoute的选择建议官方 useMatchRoute 文档 给出了明确的分工渲染期的匹配结果影响 UI使用MatchRoute组件或useMatchRoute()代价是组件订阅路由状态事件处理中的命令式检查改用useRouter()拿到的稳定 router 实例直接调用router.matchRoute({...})避免组件订阅用不到的状态import { useRouter } from tanstack/react-router function Component() { const router useRouter() return ( button onClick{() { const params router.matchRoute({ to: /posts/$postId }) // ^ { postId: 123 } }} Check current route /button ) }MatchRoute与useMatchRoute是同一套UseMatchRouteOptions选项的组件化与 hook 化两种暴露形式API 参考总览见 docs/router/api/router.md。六、常见用法模式小结结合文档示例与源码行为MatchRoute的三类典型用法条件渲染ReactNode 形态如仅在文章详情路由激活时渲染操作按钮、菜单高亮徽章。未匹配时组件输出null零 DOM 开销。始终渲染 状态感知函数形态如官方示例中的Spinner组件占位不变仅 props 随匹配结果切换回调参数必须容忍false。pending 位置预判加pending选项后在导航确认前loader 执行、redirect 处理期间即可基于目标位置渲染 UI适合“跳转途中提前显示加载态/骨架屏”的体验优化注意此时匹配对象是 pending location 而非当前位置。注意事项caseSensitive选项已标记为 deprecated大小写敏感请通过路由定义的caseSensitive或 router 的全局caseSensitive选项声明params中显式传入的值会参与精确比较与当前位置中该参数不一致时返回false官方文档示例{ postId: 789 }对比/posts/123/foo/456返回falsefuzzy: true使父路径可以匹配子位置/posts匹配/posts/123适合导航菜单中“目录级”高亮。参考路径本文对应的 API 文档docs/router/api/router/matchRouteComponent.md组件与 hook 实现packages/react-router/src/Matches.tsxuseMatchRoute位于 L158-L202MatchRoute组件位于 L228-L243匹配选项类型docs/router/api/router/MatchRouteOptionsType.md、docs/router/api/router/UseMatchRouteOptionsType.md关联 hook 文档docs/router/api/router/useMatchRouteHook.md【免费下载链接】router A client-first, server-capable, fully type-safe router and full-stack framework for the web (React and more).项目地址: https://gitcode.com/GitHub_Trending/ro/router创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
上一篇/下一篇内容由系统自动关联
返回资讯列表 →