我正在尝试学习 RTKQuery,但有些文档和示例不完整。
此链接引用了 useGetPostsQuery 但实际上并未在文档中为其定义端点。
https://redux-toolkit.js.org/rtk-query/usage/queries#selecting-data-from-a-query-result
function PostsList() {
const { data: posts } = api.useGetPostsQuery() // what does the endpoint look like?
return (
<ul>
{posts?.data?.map((post) => (
<PostById key={post.id} id={post.id} />
))}
</ul>
)
}
在没有工作示例的情况下,我正在尝试编写自己的 getMultipleItems 端点,但我看到了 TS 错误。我修改了文档 pokemon 示例以也从 api 查询列表。实时沙箱:
https://codesandbox.io/s/rtk-query-multi-fetch-poll-r4m2r
export const pokemonApi = createApi({
reducerPath: "pokemonApi",
baseQuery: fetchBaseQuery({ baseUrl: "https://pokeapi.co/api/v2/" }),
tagTypes: [],
endpoints: (builder) => ({
getPokemonByName: builder.query({
query: (name: string) => `pokemon/${name}`
}),
// this is meant to get all pokemon but is causing type errors
getAllPokemon: builder.query({
query: () => `pokemon/`
})
})
});
为了专注于相关端点,getAllPokemon 没有任何参数:
getAllPokemon: builder.query({
query: () => `pokemon/`
})
然后我尝试在这里使用它,但 useGetAllPokemonQuery 没有正确的签名并且似乎期待 args。
export const PokemonList = () => {
const { data, error, isLoading } = useGetAllPokemonQuery();
return (
<>
{error ? (
<p>Fetch error</p>
) : isLoading ? (
<p>Loading...</p>
) : data ? (
<>
<p>map pokemon here</p>
</>
) : null}
</>
);
};
我的问题是:我如何正确构造端点以在上面显示的组件示例中使用它?