开发者问题收集

清除浏览器数据后,无法读取 Object.extractRehydrationInfo 中未定义的属性(读取 [api.reducerPath])

2022-06-20
3618

我曾将 redux persist 与 RTK 查询和 redux 工具包一起使用。在从浏览器设置中手动清除浏览器数据后, 它无法重新水化 RTK 查询减速器并显示

Uncaught TypeError: Cannot read properties of undefined (reading 'notesApi')
    at Object.extractRehydrationInfo (notesApi.js:18:1)
    at createApi.ts:234:1
    at memoized (defaultMemoize.js:123:1)
    at createApi.ts:260:1
    at memoized (defaultMemoize.js:123:1)
    at createReducer.ts:239:1
    at Array.filter (<anonymous>)
    at reducer (createReducer.ts:236:1)
    at reducer (createSlice.ts:325:1)
    at combination (redux.js:560:1).

以下是 我的问题的屏幕截图

官方文档说

  • RTK Query 通过 createApi 上的 extractRehydrationInfo 选项支持重新水化。此函数在每个分派的操作中传递,并且 当它返回除 undefined 之外的值时,该值用于 重新水化已实现的 API 状态 &错误查询。

但是像我的情况那样的 undefined 值怎么办?

这是我的商店

const reducers = combineReducers({
  userReducer,
  [notesApi.reducerPath]: notesApi.reducer,
});

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(
  persistConfig,
  reducers
);

const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat(notesApi?.middleware),
});    

export default store;

这是 notesApi

export const notesApi = createApi({
 reducerPath: "notesApi" ,
  baseQuery: fetchBaseQuery({
    baseUrl: "http://localhost:5000/api/notes/",
    prepareHeaders: (headers, { getState }) => {
      const token = getState().userReducer.userInfo.token;
      console.log(token);
      if (token) {
        headers.set("authorization", `Bearer ${token}`);
      }
      return headers;
    },
  }),
  extractRehydrationInfo(action, { reducerPath }) {
    if (action.type === REHYDRATE) {
        return action.payload[reducerPath]
    }
  },
  tagTypes: ["notes"],

  endpoints: (builder) => ({
    createNote: builder.mutation({
      query: (data) => ({
        url: `/create`,
        method: "POST",
        body: data,
      }),
      invalidatesTags: ["notes"],
    }),
    getSingleNote: builder.query({
      query: (id) => ({
        url: `/${id}`,
      }),
      providesTags: ["notes"],
    })
});
export const {  useGetSingleNoteQuery,
  useCreateNoteMutation,
} = notesApi;
2个回答

我遇到过几次这个问题,当 localStorage 中没有任何东西可以补充时,尝试补充存储时似乎会出现这种情况。

错误表示在运行 extractRehydrationInfo 时无法读取未定义的 “notesApi”“notesApi” 是 API 切片的 reducerPath 值。操作的有效负载未定义。

extractRehydrationInfo(action, { reducerPath }) {
  if (action.type === REHYDRATE) {
    return action.payload[reducerPath]; // <-- action.payload undefined
  }
},

为了解决这个问题,我只需在操作有效负载上使用可选链运算符即可。

示例:

extractRehydrationInfo(action, { reducerPath }) {
  if (action.type === REHYDRATE) {
    return action.payload?.[reducerPath];
  }
},
Drew Reese
2022-07-12

我遇到了同样的问题,我只是在常量前面加上了关键字“export”

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const BASE_URL = 'http://192.168.34.62:8000/api/';

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: BASE_URL }),
  endpoints: (build) => ({
    getUserProfile: build.query({
      query: (id) => `profiles/${id}/`,
      method: 'Get',
    }),
    updateUserProfile: build.mutation({
      query: ({ id, newData }) => ({
        url: `profiles/${id}/`,
        method: 'PUT',
        body: newData,
      }),
    }),
  }),
});

export const { useGetUserProfileQuery, useUpdateUserProfileMutation } = api;
Chatelo
2024-02-05