Skip to content

useList ​

一个将数组作为状态进行管理的 React Hook。它提供高效的状态管理和稳定的操作函数。

接口 ​

ts
function useList<T>(initialState: T[] = []): UseListReturn<T>;

参数 ​

  • initialStateT[]

    初始数组状态。

返回值 ​

  • UseListReturn<T>

    包含数组状态及其操作函数的元组。

    • listReadonlyArray<T>

      当前的数组状态。

    • actions.push(value: T) => void

      将一个值追加到列表末尾。

    • actions.insertAt(index: number, value: T) => void

      在指定索引处插入一个值。

    • actions.updateAt(index: number, value: T) => void

      更新指定索引处的值。

    • actions.removeAt(index: number) => void

      移除指定索引处的值。

    • actions.setAll(values: T[]) => void

      用新数组替换整个列表。

    • actions.reset() => void

      将列表重置为其初始状态。

示例 ​

tsx
const [list, actions] = useList<string>(['apple', 'banana']);

// Add an item
actions.push('cherry');

// Insert at index
actions.insertAt(1, 'grape');

// Update at index
actions.updateAt(0, 'orange');

// Remove at index
actions.removeAt(2);

// Replace all
actions.setAll(['kiwi', 'mango']);

// Reset to initial state
actions.reset();

基于 MIT 许可证发布。