跳至主要内容

useMap

管理 Map 的 React hook。

Usage

即時編輯器
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>
  );
};
結果

Map 大小: 2

當前條目:

  • react: 18.0.0 ✓
  • vue: 3.0.0 ✓

獲取 React 版本:18.0.0

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-
ads via Carbon