框架
版本
Debouncer API 参考
Throttler API 参考
速率限制器 API 参考
队列 API 参考
批处理器 API 参考
批处理器示例

useQueuedState

函数:useQueuedState()

ts
function useQueuedState<TValue>(fn, options): [TValue[], (item, position?, runOnUpdate?) => boolean, Queuer<TValue>]
function useQueuedState<TValue>(fn, options): [TValue[], (item, position?, runOnUpdate?) => boolean, Queuer<TValue>]

定义于:react-pacer/src/queuer/useQueuedState.ts:54

一个 React 钩子,用于创建具有托管状态的队列器,将 React 的 useState 与队列功能相结合。 此钩子提供当前的队列状态和队列控制方法。

每当在队列中添加、删除或重新排序项目时,队列状态都会自动更新。 所有队列操作都反映在钩子返回的状态数组中。

可以启动和停止队列以按指定的时间间隔自动处理项目, 使其可用作调度程序。启动后,它将在每个滴答处理一个项目, 滴答之间可以有可选的等待时间。

该钩子返回一个包含以下内容的元组:

  • 当前队列状态(作为数组)
  • 具有用于队列操作的方法的队列实例

类型参数

TValue

参数

fn

(item) => void

options

QueuerOptions<TValue> = {}

返回

[TValue[], (item, position?, runOnUpdate?) => boolean, Queuer<TValue>]

示例

tsx
// 具有初始项目和优先级的基本队列
const [items, queue] = useQueuedState({
  initialItems: ['item1', 'item2'],
  started: true,
  wait: 1000,
  getPriority: (item) => item.priority
});

// 将项目添加到队列
const handleAdd = (item) => {
  queue.addItem(item);
};

// 开始自动处理
const startProcessing = () => {
  queue.start();
};

// 停止自动处理
const stopProcessing = () => {
  queue.stop();
};

// 手动处理仍然可用
const handleProcess = () => {
  const nextItem = queue.getNextItem();
  if (nextItem) {
    processItem(nextItem);
  }
};
// 具有初始项目和优先级的基本队列
const [items, queue] = useQueuedState({
  initialItems: ['item1', 'item2'],
  started: true,
  wait: 1000,
  getPriority: (item) => item.priority
});

// 将项目添加到队列
const handleAdd = (item) => {
  queue.addItem(item);
};

// 开始自动处理
const startProcessing = () => {
  queue.start();
};

// 停止自动处理
const stopProcessing = () => {
  queue.stop();
};

// 手动处理仍然可用
const handleProcess = () => {
  const nextItem = queue.getNextItem();
  if (nextItem) {
    processItem(nextItem);
  }
};