RTK 查询 createApi() 端点在 Typescript 中未显示为挂钩

aar*_*nfg 2 typescript react-native react-hooks redux-toolkit rtk-query

尝试使用 RTK 查询进行简单的基本查询,并在使用 定义我的 api 后createApi(),当我尝试解构 api 以获得我的钩子时,Typescript 给出了错误。

然后,我从文档中复制粘贴了口袋妖怪示例代码,即使这样,它也说该钩子不存在。

显然我错过了一些东西。

这是直接从文档中提取的代码,但具有字符串返回类型:

export const pokemonApi = createApi({
    reducerPath: 'pokemonApi',
    baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
    endpoints: (builder) => ({
      getPokemonByName: builder.query<string, string>({
        query: (name) => `pokemon/${name}`,
      }),
    }),
})
  
export const { useGetPokemonByNameQuery } = pokemonApi;
Run Code Online (Sandbox Code Playgroud)

useGetPokemonByNameQuery就是显示错误的原因:

Property 'useGetPokemonByNameQuery' does not exist on type 'Api<BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, { getPokemonByName: QueryDefinition<...>; }, "pokemonApi", never, unique symbol>'.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

sli*_*wp2 7

@reduxjs/工具包:1.9.5

来自/rtk-query/api/created-api/overview#react-hooks文档:

核心 RTK Query createApi 方法与 UI 无关,就像 Redux 核心库和 Redux Toolkit 与 UI 无关一样。它们都是普通的 JS 逻辑,可以在任何地方使用。

但是,RTK Query 还提供了为每个端点自动生成 React hook 的功能。由于这具体取决于 React 本身,RTK Query 提供了一个备用入口点,该入口点公开了包含该功能的 createApi 的自定义版本

如果您使用了 React 特定版本的 createApi,则生成的 Api 切片结构还将包含一组 React hooks。

相同的钩子也被添加到 Api 对象本身,并根据端点名称和查询/突变类型给出自动生成的名称。

确保createApi函数从以下路径导入:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
Run Code Online (Sandbox Code Playgroud)

不是:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
Run Code Online (Sandbox Code Playgroud)

完整的例子可以在这里找到