当我将 RTK 查询与 redux-persist 一起使用时会发生什么?

What happens when i use RTK Query with redux-persist?

当我将 Redux Toolkit Query 与 redux-persist 一起使用时会发生什么?

它会使用持久状态还是会重新获取状态?

我真的不会做。

恢复的数据可能是各种陈旧的数据,当用户按 F5 键时,他们通常希望数据是 up-to-date,而不是一周前的数据。此外,在恢复存储切片时,有关订阅的信息可能会出现问题(因为“订阅组件”从不存在,它们也永远不会卸载,因此永远不会从存储中清除)。

因此,我会将 api 切片列入黑名单,以免被持久化。

如果您希望缓存这些内容,请在您的服务器中使用缓存 headers。浏览器将为您完成所有缓存,但也允许用户清除缓存或使用 ctrl+shift+r 强制重新获取 - 因此浏览器的行为将超出用户的预期。

像这样使用extractRehydrationInfo

import { REHYDRATE } from 'redux-persist'

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  extractRehydrationInfo(action, { reducerPath }) {
    if (action.type === REHYDRATE) {
      return action.payload[reducerPath]
    }
  ...
  },

完整的官方指南here

现在有一个 official guide。在撰写本文时,您可以这样配置它:

// store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist'
import AsyncStorage from '@react-native-async-storage/async-storage'

import someSlice from 'config/features/someSlice'
import { api } from 'config/services/api'

const reducers = combineReducers({
  someSlice,
  [api.reducerPath]: api.reducer,
})

const persistConfig = {
  key: 'root',
  version: 1,
  storage: AsyncStorage,
}

const persistedReducer = persistReducer(persistConfig, reducers)

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      // Redux persist
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat(
      api.middleware,
    ),
})

export let persistor = persistStore(store)

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
// App.tsx for native or index.tsx
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,