TanStack Router NotFoundComponent 深入解析:Props 契约、错误对象与渲染链路

原创2026-09-13 15:27:191,459 阅读
文章标签:前端路由Web框架SSRUI组件

TanStack Router NotFoundComponent 深入解析:Props 契约、错误对象与渲染链路

本文基于 TanStack Router 官方 API 文档 NotFoundComponent component,系统讲解 NotFoundComponent 组件的职责、三个 Props 的完整契约(data / isNotFound / routeId),并结合 packages/router-core 与 packages/react-router 的源码,还原从 notFound() 抛错到 notFoundComponent 被渲染的完整链路,帮助你在 React 应用中精确控制"404 页面"与"资源不存在"两类未找到错误的处理方式。

1. NotFoundComponent 是什么

官方文档对 NotFoundComponent 的定义很直接:它是一个当路由上发生 not-found 错误时被渲染的组件。它是 TanStack Router 中处理"未找到"场景的核心 UI 出口,对应路由配置项 notFoundComponent(注意:文档页面描述的是组件类型本身,而你在路由上配置的是同名的选项)。

结合 Not Found Errors 指南,not-found 错误有两类来源,它们最终都由 NotFoundComponent 承接:

  • 未匹配的路径(non-matching route paths):pathname 不匹配任何已知路由模式,或仅部分匹配但多出路径段(例如存在 /posts/$postId 却访问 /posts/1/edit)。这类错误由路由器自动抛出 not-found 错误;
  • 缺失的资源(missing resources):数据层面查不到资源(例如 postId = 1 的文章不存在)。这类错误需要开发者主动在 beforeLoad 或 loader 中调用 notFound 工具函数抛出。

指南原文指出:"Under the hood, both of these cases are implemented using the same notFound function and notFoundComponent API"——两种场景底层共用同一套机制,这正是 NotFoundComponent 的统一价值所在。

2. Props 契约详解

NotFoundComponent 接收以下 Props(完整继承自官方 API 文档):

2.1 props.data

  • 类型:unknown
  • 可选
  • 在 not-found 错误被处理时传递给 notFoundComponent 的自定义数据
  • 数据来源是 NotFoundError 对象的 data 属性

这一契约在源码中得到精确印证。NotFoundError 类型定义于 packages/router-core/src/not-found.ts,其结构为:

export type NotFoundError = {
  /**
   * @deprecated
   * Use `routeId: rootRouteId` instead
   */
  global?: boolean
  /**
   * @private
   * Do not use this. It's used internally to indicate a path matching error
   */
  _global?: boolean
  data?: any
  throw?: boolean
  routeId?: RouteIds<RegisteredRouter['routeTree']>
  headers?: HeadersInit
}

可以看到 data?: any 就是官方文档中 props.data(unknown)的源头。同时 notFound() 工具函数允许你直接携带数据抛错:

// packages/router-core/src/not-found.ts
export function notFound(options: NotFoundError = {}) {
  ;(options as any).isNotFound = true
  if (options.throw) throw options
  return options
}

也就是说,你可以在 loader 中写 throw notFound({ data: { reason: 'post 1 does not exist' } }),随后 notFoundComponent 的 props.data 就能拿到这个对象。

2.2 props.isNotFound

  • 类型:boolean
  • 必填
  • 表示当前状态是否为 not-found 错误状态的布尔值
  • 该值恒为 true

"恒为 true"的原因在 not-found.ts 中一目了然:notFound() 在构造错误对象时无条件打上 isNotFound = true 标记;框架内部则通过 isNotFound(obj) 函数(obj?.isNotFound === true)识别一个错误是否为 not-found 错误。由于 NotFoundComponent 只会在被识别为 not-found 错误的情况下才被渲染,因此该 Prop 到达组件时必然为 true——它更多是错误对象自身携带的标识字段,被原样透传给了组件。

2.3 props.routeId

  • 类型:RouteIds<RegisteredRouter['routeTree']>
  • 必填
  • 正在尝试处理该 not-found 错误的路由 ID
  • 必须是路由树中的合法路由 ID 之一

在 React 实现中,routeId 的填充有明确的兜底逻辑。packages/react-router/src/Match.tsx 中的错误边界回调会先给错误补上默认路由 ID,再决定由哪个边界承接:

onCatch={(error, errorInfo) => {
  // Forward not found errors (we don't want to show the error component for these)
  if (isNotFound(error)) {
    error.routeId ??= match.routeId
    throw error
  }
  // ...
}}

error.routeId ??= match.routeId 保证了即使你没有在 notFound({ routeId }) 中显式指定目标路由,routeId 也会回落到当前 match 所在路由——这与官方文档"NotFoundError.routeId 缺省行为 + 组件侧 routeId 必填"的描述一致。而 notFound({ routeId: '/posts/$postId' }) 的显式指定能力,则允许你把错误定向抛给特定路由的 not-found 边界。

2.4 返回值

文档对组件返回值的要求是:为 not-found 场景返回合适的 UI,通常包含"页面未找到"的提示文案以及返回首页或上一级页面的导航链接。仓库中的 examples/react/basic/src/main.tsx 给出了一个规范示例:

const rootRoute = createRootRoute({
  component: RootComponent,
  notFoundComponent: () => {
    return (
      <div>
        <p>This is the notFoundComponent configured on root route</p>
        <Link to="/">Start Over</Link>
      </div>
    )
  },
})

提示文案 + 一个 <Link> 返回起点,正是文档所建议的典型形态。

3. 组件如何被调用:源码级渲染链路

理解 Props 契约之后,更有价值的是弄清楚这些 Props 从哪来、怎么传。从源码结构看,NotFoundComponent 的入参就是被展开(spread)的 NotFoundError 对象本身。

3.1 边界选择:CatchNotFound 与回退渲染

packages/react-router/src/Match.tsx 在渲染每个路由匹配时决定用哪种边界:

const routeNotFoundComponent = route.isRoot
  ? // If it's the root route, use the _notFound option, with fallback to the notFoundRoute's component
    (route.options.notFoundComponent ??
    router.options.notFoundRoute?.options.component)
  : route.options.notFoundComponent

const ResolvedNotFoundBoundary = routeNotFoundComponent
  ? CatchNotFound
  : SafeFragment

两个关键点:

  1. 根路由有历史兼容逻辑:根路由会额外回退到已废弃的 router.options.notFoundRoute(该选项在 router.ts 中被标记为 @deprecated,并指向 notFoundComponent 迁移指南)。新代码应统一使用 notFoundComponent;
  2. 只有配置了 notFoundComponent 的路由才挂 CatchNotFound 边界,否则退化为 SafeFragment,错误会向上传递给更高层的 not-found 边界。

而 Props 的实际传递发生在该文件的不 found 回退分支:

const notFoundElement = React.createElement(
  routeNotFoundComponent!,
  error as any, // <-- NotFoundError 对象被整体作为 props 传入
)

错误对象整体作为 props 传入,这正是 data、isNotFound、routeId 三个字段能"原样出现"在组件上的机制来源。

3.2 CatchNotFound:只接 notFound,其它错误继续上抛

packages/react-router/src/not-found.tsx 中的 CatchNotFound 是一个专用错误边界:

onCatch={(error, errorInfo) => {
  if (isNotFound(error)) {
    props.onCatch?.(error, errorInfo)
  } else {
    throw error
  }
}}
errorComponent={({ error }) => {
  if (isNotFound(error)) {
    return props.fallback?.(error)
  } else {
    throw error
  }
}}

它对非 not-found 错误一律 throw 上抛,确保 not-found 边界永远不会吞掉普通渲染错误——普通错误仍由 errorComponent 处理。这与指南中"notFoundComponent 与 errorComponent 职责分离"的设计一致。

3.3 无组件时的兜底:renderRouteNotFound 与开发警告

当路由 match.status === 'notFound' 但该路由没有配置 notFoundComponent 时,packages/react-router/src/renderRouteNotFound.tsx 负责兜底:

export function renderRouteNotFound(router: AnyRouter, route: AnyRoute, data: any) {
  if (!route.options.notFoundComponent) {
    if (router.options.defaultNotFoundComponent) {
      const notFoundElement = (
        <router.options.defaultNotFoundComponent {...data} />
      )
      // ...
    }
    if (process.env.NODE_ENV !== 'production') {
      if (!route.options.notFoundComponent) {
        console.warn(
          `Warning: A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<p>Not Found</p>)`,
        )
      }
    }
    return <DefaultGlobalNotFound />
  }

  const notFoundElement = <route.options.notFoundComponent {...data} />
  // ...
}

由此得到完整的三级兜底链:

  1. 路由自身的 route.options.notFoundComponent;
  2. 路由器级的 router.options.defaultNotFoundComponent(在 packages/react-router/src/router.ts 中声明为 NotFoundRouteComponent 类型);
  3. 终极兜底组件 DefaultGlobalNotFound,其实现仅一行:return <p>Not Found</p>(见 not-found.tsx)。

开发环境下若前两级都未配置,会收到明确的 console.warn 提示。另外注意非 production 环境中组件还会被 wrapInNonRouteComponentContext(notFoundElement, 'notFoundComponent') 包裹——从源码结构看,这是为了让 ESLint 插件区分"路由组件"与"非路由组件"的约束语境,开发者无需关心该细节。

4. 何时渲染:notFoundMode 与就近路由查找

NotFoundComponent 挂在哪个路由、何时渲染,由路由器的 notFoundMode 选项控制(详见 not-found-errors.md):

  • fuzzy(默认):路由树中路径不匹配时,路由器会智能地找到"最近的、配置了 notFoundComponent(或路由器配置了 defaultNotFoundComponent)的匹配路由"来承接错误。例如路由树 __root__ → posts → $postId(各级均配置了 notFoundComponent)遇到 /posts/1/edit,最终渲染结构为 <Root> → <Posts> → <Post> → <Post.notFoundComponent>——即 $postId 路由的组件,因为它是最近的已配置 not-found 组件的匹配路由。fuzzy 的初衷是尽量保留父级布局,让用户在被导向 404 时仍保有上下文;
  • root:所有 not-found 错误统一由根路由的 notFoundComponent 处理,无论最近匹配路由是谁。

fuzzy 模式下的就近查找算法在 packages/router-core/src/router.ts 中实现:当 notFoundMode !== 'root' 时,从匹配链末端向前遍历(for (let i = routes.length - 1; i >= 0; i--)),第一个配置了 options.notFoundComponent 的路由即被选中;若没有,则回退到带 children 的最近祖先路由 ID 作为承接点。

5. 完整实战示例

综合以上契约与机制,一个生产可用的配置如下(对应指南中的两个典型场景):

场景一:路径型 404(路由器自动抛出) —— 在根路由配置全局兜底:

export const Route = createRootRoute({
  component: () => <div><Outlet /></div>,
  notFoundComponent: ({ routeId, data }) => {
    // routeId: 正在处理错误的路由 ID(必有值)
    // data:    可选的自定义数据(本场景通常为 undefined)
    return (
      <div>
        <h1>Page Not Found</h1>
        <p>No route matched for this path (boundary: {routeId}).</p>
        <Link to="/">Go home</Link>
      </div>
    )
  },
})

场景二:资源型 404(loader 中主动抛出,携带 data):

import { notFound } from '@tanstack/react-router'

export const Route = createFileRoute('/posts/$postId')({
  loader: async ({ params: { postId } }) => {
    const post = await getPost(postId)
    if (!post) {
      throw notFound({
        data: { postId, message: `Post ${postId} does not exist` },
      })
    }
    return { post }
  },
  component: ({ post }) => (
    <article>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </article>
  ),
  notFoundComponent: ({ data }) => {
    // data 来自 NotFoundError.data,此处为 { postId, message }
    return <p>{(data as { message?: string })?.message ?? 'Post not found!'}</p>
  },
})

补充两个可选细节:

  • notFound(options) 支持 throw: true 直接抛出而非返回对象,支持 routeId 将错误定向到指定路由的 not-found 边界,还支持 headers 用于服务端场景的响应头设置(见 not-found.ts 中的类型定义);
  • notFoundComponent 参与路由选项的代码分割分组:packages/router-core/src/route.ts 的 codeSplitGroupings 类型显式包含 'notFoundComponent',你可以将其与 loader、component 等归入独立分片,控制 404 页面的加载粒度。

6. 小结

  • NotFoundComponent 是 TanStack Router 处理"路径不匹配"与"资源不存在"两类场景的统一 UI 出口,通过路由选项 notFoundComponent 配置;
  • 其 Props 契约由三部分构成:data(可选,源自 NotFoundError.data 的自定义数据)、isNotFound(必填,恒为 true)、routeId(必填,承接错误的路由 ID,缺省时由 error.routeId ??= match.routeId 兜底);
  • 渲染链路由 CatchNotFound 边界与 renderRouteNotFound 兜底函数共同完成,Props 本质是被整体传入的 NotFoundError 对象;兜底顺序为:路由级组件 → 路由器级 defaultNotFoundComponent → <p>Not Found</p>;
  • 承接路由的选择受 notFoundMode(fuzzy 默认 / root)控制;旧的 notFoundRoute 选项已被废弃,迁移路径见 Not Found Errors 指南。

延伸阅读:Not Found Errors 指南、NotFoundError 类型定义、react-router 不 found 渲染实现、基本示例。

登录后查看全文
router