[ PROMPT_NODE_27942 ]
js-cache-storage
[ SKILL_DOCUMENTATION ]
## 缓存 Storage API 调用
`localStorage`、`sessionStorage` 和 `document.cookie` 是同步且昂贵的。应在内存中缓存读取结果。
**错误做法(每次调用都读取存储):**
typescript
function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// 调用 10 次 = 10 次存储读取
**正确做法(使用 Map 缓存):**
typescript
const storageCache = new Map()
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // 保持缓存同步
}
使用 Map(而非 Hook)可以确保其在任何地方都能工作:工具函数、事件处理器,而不仅仅是在 React 组件中。
**Cookie 缓存:**
typescript
let cookieCache: Record | null = null
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}
**重要提示:** 如果存储可能在外部发生变化(其他标签页、服务器设置的 Cookie),请务必失效缓存:
typescript
window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})