LaoeGaoci | d077391 | 2025-06-09 00:38:40 +0800 | [diff] [blame] | 1 | import { useEffect, useState } from 'react'; |
2 | |||||
3 | export const useLocalStorage = <T>(key: string): T | null => { | ||||
4 | const [value, setValue] = useState<T | null>(null); | ||||
5 | |||||
6 | useEffect(() => { | ||||
7 | if (typeof window !== 'undefined') { | ||||
8 | const item = localStorage.getItem(key); | ||||
9 | if (item) { | ||||
10 | try { | ||||
11 | setValue(JSON.parse(item)); | ||||
12 | } catch (e) { | ||||
13 | console.error(`解析 localStorage ${key} 失败`, e); | ||||
14 | } | ||||
15 | } | ||||
16 | } | ||||
17 | }, [key]); | ||||
18 | |||||
19 | return value; | ||||
20 | }; |