持久化和重新水化
RTK Query 通过 extractRehydrationInfo
选项在 createApi
上支持重新水化。此函数传递给每个分派的 action,并且当它返回的值不是 undefined
时,该值将用于重新水化已完成和出错查询的 API 状态。
另请参阅 服务器端渲染。
信息
通常,不建议持久化 API 切片,而应该在浏览器中使用 Cache-Control
头部 来定义缓存行为。如果用户长时间未访问页面,持久化和重新水化 API 切片可能会导致用户始终使用非常陈旧的数据。但是,在像原生应用程序这样的环境中,由于没有浏览器缓存来处理此问题,持久化仍然可能是一个可行的选择。
Redux Persist
API 状态重新水化可以与 Redux Persist 结合使用,方法是利用从 redux-persist
导入的 REHYDRATE
操作类型。在持久化根 reducer 时,可以使用 autoMergeLevel1
或 autoMergeLevel2
状态协调器 开箱即用,或者在仅持久化 API reducer 时使用 autoMergeLevel1
协调器。
- TypeScript
- JavaScript
redux-persist 重新水化示例
import type { Action } from '@reduxjs/toolkit'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { REHYDRATE } from 'redux-persist'
type RootState = any // normally inferred from state
function isHydrateAction(action: Action): action is Action<typeof REHYDRATE> & {
key: string
payload: RootState
err: unknown
} {
return action.type === REHYDRATE
}
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
// to prevent circular type issues, the return type needs to be annotated as any
extractRehydrationInfo(action, { reducerPath }): any {
if (isHydrateAction(action)) {
// when persisting the api reducer
if (action.key === 'key used with redux-persist') {
return action.payload
}
// When persisting the root reducer
return action.payload[api.reducerPath]
}
},
endpoints: (build) => ({
// omitted
}),
})
redux-persist 重新水化示例
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { REHYDRATE } from 'redux-persist'
function isHydrateAction(action) {
return action.type === REHYDRATE
}
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
// to prevent circular type issues, the return type needs to be annotated as any
extractRehydrationInfo(action, { reducerPath }) {
if (isHydrateAction(action)) {
// when persisting the api reducer
if (action.key === 'key used with redux-persist') {
return action.payload
}
// When persisting the root reducer
return action.payload[api.reducerPath]
}
},
endpoints: (build) => ({
// omitted
}),
})