useMap

管理 Map 的 React hook。

useMap 提供一個響應式的 Map 資料結構。它回傳一個包含 Map 實例和操作函式(setdeleteclearreset)的元組。每次修改操作都會觸發重新渲染以反映最新狀態。

使用場景

  • 管理鍵值對集合並在值變更時觸發 UI 更新
  • 建構需要高效查找和更新的標籤系統或篩選器
  • 替代使用物件來管理動態鍵值對資料

注意事項

  • 不可變更新:每次修改操作會建立新的 Map 實例以觸發 React 重新渲染。
  • 初始值:接受初始鍵值對作為建構參數。
  • 相關 hooks:另請參閱 useSetState 用於物件狀態的部分更新。

Usage

Live Editor
function Demo() {
  const { map, set, get, remove, has, clear, reset, size } = useMap([
    ['react', '18.0.0'],
    ['vue', '3.0.0'],
  ]);

  return (
    <div>
      <p>Map 大小: {size}</p>
      <div style={{ marginBottom: 16 }}>
        <button
          type="button"
          onClick={() => set('angular', '16.0.0')}
          style={{ marginRight: 8 }}
        >
          添加 Angular
        </button>
        <button
          type="button"
          onClick={() => set('react', '18.2.0')}
          style={{ marginRight: 8 }}
        >
          更新 React
        </button>
        <button
          type="button"
          onClick={() => remove('vue')}
          style={{ marginRight: 8 }}
        >
          刪除 Vue
        </button>
        <button
          type="button"
          onClick={clear}
          style={{ marginRight: 8 }}
        >
          清空所有
        </button>
        <button
          type="button"
          onClick={reset}
          style={{ marginRight: 8 }}
        >
          重置
        </button>
      </div>
      <div>
        <p>當前條目:</p>
        <ul>
          {Array.from(map.entries()).map(([key, value]) => (
            <li key={key}>
              {key}: {value} 
              {has(key) && ' ✓'}
            </li>
          ))}
        </ul>
      </div>
      <div>
        <p>獲取 React 版本:{get('react') || '未找到'}</p>
      </div>
    </div>
  );
};
Result

API

useMap

Returns

{ readonly map: Map<K, V>; readonly set: (key: K, value: V) => void; readonly get: (key: K) => V | undefined; readonly remove: (key: K) => boolean; readonly has: (key: K) => boolean; readonly clear: () => void; readonly reset: () => void; readonly size: number; }: 包含以下屬性的對象:

  • map: 當前的 Map 實例。
  • set: 在 map 中設定鍵值對的函數。
  • get: 通過鍵從 map 中獲取值的函數。
  • remove: 從 map 中刪除鍵並返回是否存在的函數。
  • has: 檢查鍵是否存在於 map 中的函數。
  • clear: 清除 map 中所有條目的函數。
  • reset: 將 map 重置為其初始狀態的函數。
  • size: map 的當前大小。

Arguments

參數名描述類型預設值
initialValue初始值,可以为 Map 实例、数组或者一个初始化的函数Map<K, V> | readonly (readonly [K, V])[] | (() => Map<K, V> | readonly (readonly [K, V])[]) | undefined-