我正在尝试使用 redux 工具包进行 api 调用,但在调度时出现此错误
无法读取未定义的属性(读取“订阅”)
index.ts
import api from "./api";
export const { useFetchAllMaterialsQuery } = api;
api.ts
import { createApi } from "@reduxjs/toolkit/query/react";
import type { OperationsEntity } from "models";
import { fetchAxiosBaseQuery, getCookie } from "services/httpService";
// Create api endpoints
export default createApi({
reducerPath: "fetchAllMaterialsReportApi",
baseQuery: fetchAxiosBaseQuery({ baseUrl: getCookie("apiUrl") }),
endpoints: (builder) => ({
/**
* Fetch list of operations that have material(s).
*/
fetchAllMaterials: builder.query<OperationsEntity[], string | number>({
query: (id) => ({
url: `/v2/myendpoint/${id}/mydata`,
}),
}),
}),
});
选择器.ts
import { useSelectedProjectId } from "hooks";
import { useAppSelector } from "redux/store";
import api from "./api";
/**
* @returns Safran pending count.
*/
export function useAllMaterialOperations() {
const projectId = useSelectedProjectId();
return useAppSelector(
(state: any) =>
api.endpoints.fetchAllMaterials.select(projectId!)(state).data || []
);
}
/**
* @returns true if the fetch materials are in loading status (fetching), false otherwise.
*/
export function useAllMaterialOperationsLoading() {
const projectId = useSelectedProjectId();
return useAppSelector(
(state: any) =>
{
return api.endpoints.fetchAllMaterials.select(projectId!)(state).isLoading;
}
);
}
/**
* @returns the data and the loading status of the fetch materials call.
*/
export function useFetchAllMaterialsWithLoadingStatus() {
const data = useAllMaterialOperations();
const isLoading = useAllMaterialOperationsLoading();
return {
data,
isLoading,
};
}
fetch 查询导致应用程序崩溃并像这样被调用:
const MyComp = ({ data }) => {
const id = useId();
const materialDataQuery = useFetchAllMaterialsQuery(id);
}
代码中是否有明显的错误导致此错误?
我想你需要配置商店:
import { yourApi} from './services/yourApi'
export const store = configureStore({
reducer: {
// Add the generated reducer as a specific top-level slice
[yourApi.reducerPath]: yourApi.reducer,`enter code here`
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(yourApi.middleware),
})