React Redux 工具包查询不缓存数据

问题描述 投票:0回答:2

我在 React 应用程序中使用 @reduxjs/toolkit/query 从我的 API 获取数据。我正在使用 useQuery 挂钩来执行查询,但数据没有按预期进行缓存。

这是我的代码:

// Define the API using createApi
export const defaultApi = createApi({
  reducerPath: 'defaultApi',
  baseQuery: fetchBaseQuery({
    baseUrl: process.env.REACT_APP_API_URL,
    prepareHeaders: (headers, { getState }) => {
      const {
        auth: { accessToken }
      } = getState() as any
      if (accessToken) {
        headers.set('Authorization', `Bearer ${accessToken}`)
      }
      return headers
    }
  }),
  endpoints: (builder) => ({
    products: builder.query<Product[], void>({
      query: () => {
        return {
          url: `/api/user/products`,
          providesTags: ['products'],
        }
      }
    })
  }),
})

我的店铺:

import { AnyAction, configureStore, ThunkDispatch } from "@reduxjs/toolkit";
import { defaultApi } from "apis/default";
import { useDispatch } from "react-redux";
import {
  createMigrate,
  FLUSH,
  PAUSE,
  PERSIST, PersistedState, persistReducer,
  persistStore,
  PURGE,
  REGISTER,
  REHYDRATE
} from "redux-persist";
import storage from "redux-persist/lib/storage";
import rootReducer from "./rootReducer";

const migrations = {
  0: (state: PersistedState) => {
    return {
      _persist: {
        rehydrated: true,
        version: state?._persist?.version ?? 0,
      },
    };
  },
};

const persistConfig = {
  key: "primary",
  version: 15,
  storage,
  migrate: createMigrate(migrations, { debug: false }),
  whitelist: [
    "auth",
  ],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

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

export default store;



type TypedDispatch<T> = ThunkDispatch<T, any, AnyAction>;

export type RootState = ReturnType<typeof store.getState>;
export const useAppDispatch = () => useDispatch<TypedDispatch<RootState>>();

const persistor = persistStore(store);

export { persistor };

我的组件:

// Use the query in a component
const MyComponent = () => {
  const {
    data: products,isLoading,isSuccess,isFetching
  } = useProductsQuery();
  
  useEffect(() => {
    console.log("🚀 ~ file: index.tsx:22 ~ isLoading:", isLoading)
    console.log("🚀 ~ file: index.tsx:22 ~ isSuccess:", isSuccess)
    console.log("🚀 ~ file: index.tsx:22 ~ isFetching:", isFetching)
  },[isLoading,isSuccess,isFetching])
  // ...
}

我知道请求是通过观看“网络”选项卡发出的,而且每次刷新页面时,控制台都会返回:

🚀正在加载:真

🚀 是成功:假

🚀 isFetching: true

🚀 isLoading: false

🚀 isSuccess: true

🚀 isFetching:false

已经尝试将 providesTags 设置为 [] 和 cacheTime: 3600000 // 缓存 1 小时

我希望只有在我第一次加载页面时才会调用端点。

reactjs react-redux rtk-query
2个回答
0
投票

RTK 查询,就像 Redux 本身一样,是一个内存缓存。当您在应用程序中导航时,它会保留数据(假设您使用路由器库正确导航)。

当你按 F5 时,你会杀死整个应用程序并重新启动它。在这种情况下,所有内存都已被擦除,需要重新获取数据。


0
投票

您使用的库提供了内存缓存,这意味着只要您的页面处于活动状态,缓存就处于活动状态。每次刷新页面时都会清除缓存并启动网络提取。

如果您想在页面刷新/重新加载时保留网络获取的数据,您可以尝试使用浏览器存储选项,如 localstorage、sessionstorage、indexeddb 等。

以下是一些可能对您有帮助的链接:

© www.soinside.com 2019 - 2024. All rights reserved.