dehydrate 会创建一个缓存的冻结表示,之后可以用 HydrationBoundary 或 hydrate 来进行水合。这对于将预取的查询从服务器传递到客户端,或将查询持久化到 localStorage 或其他持久化位置非常有用。默认情况下,它只包含当前成功的查询。
import { dehydrate } from '@tanstack/react-query'
const dehydratedState = dehydrate(queryClient, {
shouldDehydrateQuery,
shouldDehydrateMutation,
})
import { dehydrate } from '@tanstack/react-query'
const dehydratedState = dehydrate(queryClient, {
shouldDehydrateQuery,
shouldDehydrateMutation,
})
选项
Returns (返回)
某些存储系统(例如浏览器 Web Storage API)要求值是 JSON 可序列化的。如果您需要脱水那些不能自动序列化为 JSON 的值(例如 Error 或 undefined),您必须自己进行序列化。由于默认只包含成功的查询,要也包含 Errors,您必须提供 shouldDehydrateQuery,例如:
// server
const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors
const serializedState = mySerialize(state) // transform Error instances to objects
// client
const state = myDeserialize(serializedState) // transform objects back to Error instances
hydrate(client, state)
// server
const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors
const serializedState = mySerialize(state) // transform Error instances to objects
// client
const state = myDeserialize(serializedState) // transform objects back to Error instances
hydrate(client, state)
hydrate 将先前脱水状态添加到 cache 中。
import { hydrate } from '@tanstack/react-query'
hydrate(queryClient, dehydratedState, options)
import { hydrate } from '@tanstack/react-query'
hydrate(queryClient, dehydratedState, options)
选项
如果您尝试水合的查询已存在于 queryCache 中,hydrate 将仅在数据比缓存中现有数据更新时才覆盖它们。否则,它将不会应用。
HydrationBoundary 会将先前脱水状态添加到 queryClient 中,该状态由 useQueryClient() 返回。如果客户端已包含数据,则新查询将根据更新时间戳智能合并。
import { HydrationBoundary } from '@tanstack/react-query'
function App() {
return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
}
import { HydrationBoundary } from '@tanstack/react-query'
function App() {
return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
}
注意:HydrationBoundary 只能脱水 queries。
选项