访问RTK查询数据&跨多个组件的状态

发布于 2025-02-13 11:08:29 字数 338 浏览 2 评论 0原文

我正在使用RTK查询来获取一些数据。我需要在应用程序中的各个组件上访问加载状态,但是我不确定如何这样做。

我觉得可能只是我误解了如何在较大的应用程序中正确使用RTK查询。大多数示例都是一个组件,我不太了解如何从各个组件中访问单个查询的各个状态。

例如,我需要在应用程序的主要部分中显示一个从查询生成数据的主要部分。然后,我需要在侧边栏的一个小部分中显示一个完全不同的加载程序,该侧边栏的一个内容细节是通过相同的API查询生成的。

这是如何与RTK查询一起使用的?
是否存在使用多个共享此查询状态/状态的多个组件的示例?
我是否完全缺少对整个应用程序中如何使用状态的基本了解? (我觉得这是这里的东西哈哈)

I'm using RTK Query to fetch some data. I need to access the loading state across various components in my application, but I'm unsure how to do so.

I feel like it may simply be that I'm misunderstanding how to utilize RTK Query properly in a larger application. Most of the examples are a single component, and I don't quite see how you can get access to the various states of a single query from various components.

For example, I need to show a loader in a main section of the app where the data is generated from a query. Then, I need to show a completely different loader in a tiny part of a sidebar, which has some content details which is generated via the same API query.

How does this work with RTK Query?
Do any examples exist which use multiple components that share this query state/status?
Am I completely missing a fundamental understanding of how state is used across the app? (I feel this is the thing here haha)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

离去的眼神 2025-02-20 11:08:29

如果您调用相同的usequery在另一个组件中使用相同参数的挂钩,则这两个将共享缓存条目并返回完全相同的数据 - 它不会触发另一个请求到服务器。

因此:只有usequery到处都需要它:)

If you call the same useQuery hook with the same arguments in another component, those two will share the cache entry and return exactly the same data - it will not trigger another request to the server.

So: just useQuery everywhere you need it :)

jJeQQOZ5 2025-02-20 11:08:29

您还可以为该“加载”件定义选择器,如果您不使用每个组件中的查询,则可以像这样:

const selectIsResourceLoading = (state: RootState) => apiSlice.endpoints.getResource.select()(state).isLoading;

然后在组件中重复使用它:

const isResourceLoading = useTypedSelector(selectIsResourceLoading);

You can also define a selector for that "loading" piece, if you don't wan't to use the query inside every component, like so:

const selectIsResourceLoading = (state: RootState) => apiSlice.endpoints.getResource.select()(state).isLoading;

And then, reuse it within the component:

const isResourceLoading = useTypedSelector(selectIsResourceLoading);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文