使用 TanStack Router 进行可靠的查询预取

Aug 18, 2026 — , ,

2026年8月18日 — , ,

Reliable Query Prefetching with TanStack Router

Photo by Mario Heller

摄影:Mario Heller

In the last blog post of this series, I described all the advantages of the imo recommended pattern to do data fetching in TanStack Router with TanStack Query. To recap, it’s about triggering fetches as early as possible in the loader, but also about treating the loader as an event handler so that components can “pick up” the promise with useSuspenseQuery or useQuery.

在本系列的上一篇博客文章中,我描述了在 TanStack Router 中使用 TanStack Query 进行数据获取的我认为推荐的模式的所有优点。回顾一下,它涉及在 loader 中尽早触发 fetch,同时也将 loader 视为事件处理程序,以便组件可以使用 useSuspenseQueryuseQuery “获取” promise。

The takeaway here should be that a component should, if possible, probably never initiate data fetching on its own. Yes, it’s great in theory that you have a fully self-contained component that has its own data requirements and resolves them automatically when it renders. But in practice, if that’s the only place where we fetch, we are 1) doing this probably way later than we ideally should and 2) we can easily introduce fetch waterfalls (with or without suspense).

这里得出的结论应该是,如果可能的话,组件永远不应该自己发起数据获取。是的,理论上拥有一个完全自包含的组件,它有自己的数据需求并在渲染时自动解析它们,这听起来很棒。但在实践中,如果这是我们唯一进行 fetch 的地方,我们 1) 这样做的时间可能比理想情况下晚得多,而且 2) 我们很容易引入 fetch waterfalls(无论是否使用 suspense)。

So, route loader to the rescue. 🎉 As usual, there is a cost to it though:

所以,route loader 来救场了。🎉 不过和往常一样,这也是有代价的:

The big drawback of this approach is that you essentially duplicate what you do in the component in a second location - the route loader. Now duplication is not the end of the world, and it’s a fine trade-off for the UX you are giving your app, but there is one thing that’s really critical to keep in mind as your app grows:

这种方法的一个主要缺点是,你本质上在第二个位置——route loader中复制了在组件中所做的事情。现在,重复并不是世界末日,对于你为应用提供的 UX 来说,这是一个很好的权衡,但随着应用的增长,有一件事是真正需要牢记在心的:

Those two places have to be 100% in sync

这两个地方必须 100% 保持同步

And usually, over time, this gets harder to ensure. Minimal examples are great for blogposts, but they don’...

开通本站会员,查看完整译文。

Главная - Вики-сайт
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-29 09:46
浙ICP备14020137号-1 $Гость$