我目前正在将React Redux RTK实现到我的React应用程序中,我在获取数据时遇到了问题。
我想创建一个端点,其中查询需要多个参数才能工作。例如,端点是https://localhost:8080/object/id
,其中Object和Id是我需要从中获取数据的参数。
我已经为查询创建了一个这样的接口:
export interface ISearch {
objectName: string,
id: string
}
我的apiSlice看起来像这样:
import {createApi, fetchBaseQuery} from "@reduxjs/toolkit/query";
import {ISearch} from "../utils/Interfaces";
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({
baseUrl: 'https://localhost:8080/api/v1'
}),
tagTypes: ['Record'],
endpoints: builder => ({
getRecord: builder.query({
query: (params: ISearch) => `/${params.objectName}/${params.id}`,
providesTags: (result, error, arg) => [{
type: 'Record',
id: arg
}]
})
})
})
唯一的问题是我在providesTags
函数上得到以下错误:
TS2322: Type '(result: any, error: FetchBaseQueryError, arg: ISearch) => { type: "Record"; id: ISearch; }[]' is not assignable to type 'ResultDescription<"ObjectDefinition" | "Record", any, ISearch, FetchBaseQueryError, FetchBaseQueryMeta>'. Type '(result: any, error: FetchBaseQueryError, arg: ISearch) => { type: "Record"; id: ISearch; }[]' is not assignable to type 'GetResultDescriptionFn<"ObjectDefinition" | "Record", any, ISearch, FetchBaseQueryError, FetchBaseQueryMeta>'. Type '{ type: "Record"; id: ISearch; }[]' is not assignable to type 'readonly TagDescription<"ObjectDefinition" | "Record">[]'. Type '{ type: "Record"; id: ISearch; }' is not assignable to type 'TagDescription<"ObjectDefinition" | "Record">'. Type '{ type: "Record"; id: ISearch; }' is not assignable to type 'FullTagDescription<"ObjectDefinition" | "Record">'. Types of property 'id' are incompatible. Type 'ISearch' is not assignable to type 'string | number'. Type 'ISearch' is not assignable to type 'number'.
2条答案
按热度按时间ua4mk5z41#
查询标记由类型和字符串id组成。
providesTags
函数中的arg
就是query
函数中的params
。因此,您可能希望使用arg.id
或类似arg.object + '/' + arg.id
的连接字符串,而不是使用arg
作为id
?qxgroojn2#
对于任何为此而挣扎的人,我发现了一个小花絮,可能会帮助某人......尝试在标记定义中设置
type: 'Record' as const
......似乎在RTK查询中,使用数字动态设置id
,而不是在标记定义中使用as const
似乎已经创建了类型不等式。