LaoeGaoci | d077391 | 2025-06-09 00:38:40 +0800 | [diff] [blame] | 1 | import { useEffect, useState } from 'react'; |
| 2 | |
Seamher | bb14ecb | 2025-06-09 22:37:20 +0800 | [diff] [blame] | 3 | // export const useLocalStorage = <T>(key: string): T | null => { |
| 4 | // const [value, setValue] = useState<T | null>(null); |
LaoeGaoci | d077391 | 2025-06-09 00:38:40 +0800 | [diff] [blame] | 5 | |
Seamher | bb14ecb | 2025-06-09 22:37:20 +0800 | [diff] [blame] | 6 | // useEffect(() => { |
| 7 | // if (typeof window !== 'undefined') { |
| 8 | // const item = localStorage.getItem(key); |
| 9 | // if (item) { |
| 10 | // try { |
| 11 | // setValue(JSON.parse(item)); |
| 12 | // console.log(JSON.parse(item)); |
| 13 | // } catch (e) { |
| 14 | // console.error(`解析 localStorage ${key} 失败`, e); |
| 15 | // } |
| 16 | // } |
| 17 | // } |
| 18 | // }, [key]); |
| 19 | |
| 20 | // return value; |
| 21 | // }; |
| 22 | |
| 23 | export const useLocalStorage = <T>(key: string): T | null => { |
| 24 | const isClient = typeof window !== 'undefined'; |
| 25 | const [value, setValue] = useState<T | null>(() => { |
| 26 | if (isClient) { |
LaoeGaoci | d077391 | 2025-06-09 00:38:40 +0800 | [diff] [blame] | 27 | const item = localStorage.getItem(key); |
| 28 | if (item) { |
| 29 | try { |
Seamher | bb14ecb | 2025-06-09 22:37:20 +0800 | [diff] [blame] | 30 | return JSON.parse(item); |
LaoeGaoci | d077391 | 2025-06-09 00:38:40 +0800 | [diff] [blame] | 31 | } catch (e) { |
| 32 | console.error(`解析 localStorage ${key} 失败`, e); |
| 33 | } |
| 34 | } |
| 35 | } |
Seamher | bb14ecb | 2025-06-09 22:37:20 +0800 | [diff] [blame] | 36 | return null; |
| 37 | }); |
| 38 | |
| 39 | useEffect(() => { |
| 40 | if (!isClient) return; |
| 41 | const item = localStorage.getItem(key); |
| 42 | if (item) { |
| 43 | try { |
| 44 | setValue(JSON.parse(item)); |
| 45 | } catch (e) { |
| 46 | console.error(`解析 localStorage ${key} 失败`, e); |
| 47 | } |
| 48 | } |
LaoeGaoci | d077391 | 2025-06-09 00:38:40 +0800 | [diff] [blame] | 49 | }, [key]); |
| 50 | |
| 51 | return value; |
| 52 | }; |