如何在 RTK 查询中为 fetchBaseQuery 添加默认选项?

How to add default options for fetchBaseQuery in RTK Query?

在网上找了半天,没找到能不能像axios一样给这个库加上默认选项?每次创建 Api 时是否都必须将相同的选项传递给 fetchBaseQuery?

几乎在所有情况下,您都应该在应用程序中只创建一个 API,因此实际上不需要“默认值”。您创建的 fetchBaseQuery 已经是默认值。

如果这些是完全独立的数据集,您应该只创建多个 api。因此,如果您有一个 api 查询 facebook 服务,另一个查询蛋糕食谱服务,那很好。但它是同一个数据库,你为作者创建一个 api,为书籍创建一个,你没有按预期使用它。

RTK 查询文档中大约 5 个不同的地方也提到了这一点,例如引用 Quick Start Tutorial:

Typically, you should only have one API slice per base URL that your application needs to communicate with. For example, if your site fetches data from both /api/posts and /api/users, you would have a single API slice with /api/ as the base URL, and separate endpoint definitions for posts and users. This allows you to effectively take advantage of automated re-fetching by defining tag relationships across endpoints.

For maintainability purposes, you may wish to split up endpoint definitions across multiple files, while still maintaining a single API slice which includes all of these endpoints. See code splitting for how you can use the injectEndpoints property to inject API endpoints from other files into a single API slice definition.