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> ); };
结果
Loading...
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 中获取值的函数。
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| initialValue | 初始值,可以为 Map 实例、数组或者一个初始化的函数 | Map<K, V> | readonly (readonly [K, V])[] | (() => Map<K, V> | readonly (readonly [K, V])[]) | undefined | - |