无法读取未定义的属性(阅读“subscriptions”)- React redux工具包

798qvoo8  于 2023-03-08  发布在  React
关注(0)|答案(1)|浏览(129)

我尝试使用redux工具包执行api调用,但在调度时收到此错误
无法读取未定义的属性(正在读取"subscriptions")

    • 索引. 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,
  };
}

获取查询导致应用崩溃,调用方式如下:

const MyComp = ({ data }) => {
  const id = useId();
  const materialDataQuery = useFetchAllMaterialsQuery(id);

}

代码中是否存在导致此错误的明显错误?

mnowg1ta

mnowg1ta1#

我想您需要配置存储:

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),
})

相关问题