框架
版本

NotifyManager

The notifyManager 处理 Tanstack Query 中的回调调度和批处理。

它公开了以下方法

notifyManager.batch

batch 可用于批量处理在传递的回调中调度的所有更新。这主要在内部用于优化 queryClient 更新。

ts
function batch<T>(callback: () => T): T
function batch<T>(callback: () => T): T

notifyManager.batchCalls

batchCalls 是一个高阶函数,它接受一个回调并包装它。所有对包装函数的调用都会调度回调在下一个批次中运行。

ts
type BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void

function batchCalls<T extends Array<unknown>>(
  callback: BatchCallsCallback<T>,
): BatchCallsCallback<T>
type BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void

function batchCalls<T extends Array<unknown>>(
  callback: BatchCallsCallback<T>,
): BatchCallsCallback<T>

notifyManager.schedule

schedule 调度一个函数在下一个批次中运行。默认情况下,批处理使用 setTimeout 运行,但这可以配置。

ts
function schedule(callback: () => void): void
function schedule(callback: () => void): void

notifyManager.setNotifyFunction

setNotifyFunction 覆盖 notify 函数。当应该执行回调时,此函数会传递回调。默认的 notifyFunction 只是调用它。

这可以用于例如在使用 React.act 运行测试时包装通知

ts
import { notifyManager } from '@tanstack/react-query'
import { act } from 'react-dom/test-utils'

notifyManager.setNotifyFunction(act)
import { notifyManager } from '@tanstack/react-query'
import { act } from 'react-dom/test-utils'

notifyManager.setNotifyFunction(act)

notifyManager.setBatchNotifyFunction

setBatchNotifyFunction 设置用于批量更新的函数

如果您的框架支持自定义批处理函数,您可以通过调用 notifyManager.setBatchNotifyFunction 让 TanStack Query 知道它。

例如,这就是在 solid-query 中设置 batch 函数的方式

ts
import { notifyManager } from '@tanstack/query-core'
import { batch } from 'solid-js'

notifyManager.setBatchNotifyFunction(batch)
import { notifyManager } from '@tanstack/query-core'
import { batch } from 'solid-js'

notifyManager.setBatchNotifyFunction(batch)

notifyManager.setScheduler

setScheduler 配置一个自定义回调,该回调应调度何时运行下一个批次。默认行为是 setTimeout(callback, 0)

ts
import { notifyManager } from '@tanstack/react-query'

// Schedule batches in the next microtask
notifyManager.setScheduler(queueMicrotask)

// Schedule batches before the next frame is rendered
notifyManager.setScheduler(requestAnimationFrame)

// Schedule batches some time in the future
notifyManager.setScheduler((cb) => setTimeout(cb, 10))
import { notifyManager } from '@tanstack/react-query'

// Schedule batches in the next microtask
notifyManager.setScheduler(queueMicrotask)

// Schedule batches before the next frame is rendered
notifyManager.setScheduler(requestAnimationFrame)

// Schedule batches some time in the future
notifyManager.setScheduler((cb) => setTimeout(cb, 10))