尚未安装 TanStack Pacer?请参阅安装页面获取说明。
仍在学习 TanStack Pacer 是什么以及如何帮助您的应用程序?请参阅我应该选择哪个 Pacer 工具?指南,以帮助您选择要使用的 Pacer 工具。TanStack Pacer 库具有 5 个核心工具,并且每种工具都有相当灵活的使用方式。熟悉上述指南将帮助您为您的用例选择合适的工具。
请参阅API 参考页面,以获取每个 Pacer 工具的完整 API 参考列表。
如果您使用的是纯 JavaScript,则可以使用核心 pacer 包中的核心类和函数。
import { Debouncer } from '@tanstack/pacer' // class
const debouncer = new Debouncer(fn, options)
debouncer.maybeExecute(args) // execute the debounced function
debouncer.cancel() // cancel the debounced function
debouncer.flush() // flush the debounced function
import { debounce } from '@tanstack/pacer' // function
const debouncedFn = debounce(fn, options)
debouncedFn(args) // execute the debounced function
如果您使用的是 React 等框架适配器,可以使用 useDebouncer hook 创建一个防抖函数。
import { useDebouncer } from '@tanstack/react-pacer'
const debouncer = useDebouncer(fn, options) // recommended
debouncer.maybeExecute(args) // execute the debounced function
debouncer.cancel() // cancel the debounced function
debouncer.flush() // flush the debounced function
如果您希望以类型安全的方式定义 pacer 工具的常用选项,TanStack Pacer 为每个工具提供选项助手。
import { debouncerOptions } from '@tanstack/pacer'
const commonDebouncerOptions = debouncerOptions({
wait: 1000,
leading: false,
trailing: true,
})
const debouncer = new Debouncer(fn, { ...commonDebouncerOptions, key: 'myDebouncer' })
在每个框架适配器中,都有一个提供器组件,您可以使用它为 pacer 工具的所有实例提供默认选项。
import { PacerProvider } from '@tanstack/react-pacer'
// set default options for react-pacer instances
<PacerProvider defaultOptions={{ debouncer: { wait: 1000 } }}>
<App />
</PacerProvider>
TanStack Pacer 为每个框架适配器提供官方 TanStack Devtools 集成。请参阅Devtools文档,了解有关如何设置和使用 Pacer devtools 的更多信息。