Redux Toolkit:如何在官方文档中编写getposts端点



我正在尝试学习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错误。我修改了文档口袋妖怪的例子,也从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没有正确的签名,似乎期待参数。

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}
</>
);
};

我的问题是:我如何正确地构造端点以在上面显示的组件示例中使用它?

在你的例子中:

getAllPokemon: builder.query<YourResultType, void>({
query: () => `pokemon/`
})

使用void作为参数类型

无论如何,https://github.com/reduxjs/redux-toolkit/tree/master/examples/query/react下面的所有例子都是用TypeScript写的。你可能会想看看那些

最新更新