0

不知道如何在请求后访问标头。不使用的文档示例x-total-count

const guitarApi = createApi({
  reducerPath: 'GUITARS',
  baseQuery: fetchBaseQuery({ baseUrl: API_URL }),
  endpoints: (builder) => ({
    getAllGuitars: builder.query<AllGuitarsResponse, number>({
      query: (limit = 1) => `${APIRoute.Guitars}_limit${limit}`,
    }),
  }),
});

我让它们像这样进入组件

const { data: guitarData } = useGetAllGuitarsQuery(searchingParams);

我在哪里可以访问响应标头?

4

1 回答 1

1

你可以用transformResponse这个,它有签名

  transformResponse?(
    baseQueryReturnValue: BaseQueryResult<BaseQuery>,
    meta: BaseQueryMeta<BaseQuery>,
    arg: QueryArg
  ): ResultType | Promise<ResultType>

如果你使用fetchBaseQuery,meta将是

type FetchBaseQueryMeta = { request: Request; response?: Response }

因此,您可以像这样编写端点:

const guitarApi = createApi({
  reducerPath: 'GUITARS',
  baseQuery: fetchBaseQuery({ baseUrl: API_URL }),
  endpoints: (builder) => ({
    getAllGuitars: builder.query<{ apiResponse: AllGuitarsResponse, totalCount: number}, number>({
      query: (limit = 1) => `${APIRoute.Guitars}_limit${limit}`,
      transformResponse(apiResponse, meta) {
        return { apiResponse, totalCount: Number(meta.response.headers.get('X-Total-Count')) }
      }
    }),
  }),
});
于 2021-12-19T08:41:56.257 回答