我一直在使用 RTK 查询创建 React Typescript 应用程序,并且我想实现自定义选择器。 但要实现它,我需要从另一个端点获取一些数据:
store.dispatch(userApiSlice.endpoints.check.initiate(undefined))
const data = userApiSlice.endpoints.check.getSomeData
export const selectCartItemsResult = cartApiSlice.endpoints.getCartItems
.select(data?.user?.id ?? skipToken)
我找到了解决方案这里。他们的解决方案如下所示:
class TodoService {
getSelectorForTodo(todoId: string) {
if (this._lastId !== todoId)
this._lastSelector = api.endpoints.getTodo.select( {id: todoId } )
return this._lastSelector
}
getTodoTitle( todoId: string ) {
const todo = this.getSelectorForTodo(todoId)(state)
return todo.data.title
}
}
我不知道从哪里获取状态变量。所以我把里面的
store.getState()
来了,但这给出了以下错误:
const data = userApiSlice.endpoints.check
.select(undefined)(store.getState())
-->
“api.queries”的类型在这些类型之间不兼容。
输入 'QueryState<{ getCartItems: QueryDefinition
我对如何获取状态变量没有其他想法。请问,您能给出一些使用打字稿编译但也声明状态变量的示例吗?
我不知道您需要什么所有 RTK 查询实现。所以我会在需要的时候添加它
编辑:cartApiSlice 和 userApiSlice 是使用
injectEndpoints
创建的。
因为您的
userApiSlice
在创建状态后被注入到您的 api 中,所以 TypeScript 无法知道此处添加了某些内容 - 所以它会抱怨,因为“类型中”的 api 没有那些额外的端点。
这并不意味着它不起作用 - 只是 TypeScript 在这里抱怨。
在这种情况下,你无法回避告诉 TypeScript“我比你更了解”——做一个断言
as any
。
const data = userApiSlice.endpoints.check
.select(undefined)(store.getState() as any)
你可以这样做:
import { userApi } from 'src/app-redux/services/userAPI';
import { store } from 'src/app-redux/store';
.
.
// Adding a cache subscription
const promise = store.dispatch(userApi.endpoints.getSomeData.initiate('hello'));
const { refetch } = promise;
// interact with the cache in the same way as you would with a useFetch...() hook
const { data, isLoading, isSuccess /*...*/ } = await promise;
// do stuff with data
// Removing the corresponding cache subscription
promise.unsubscribe();
.
.
正如官方文档中提到的: https://redux-toolkit.js.org/rtk-query/usage/usage-without-react-hooks