| import { useEffect, useState } from 'react'; |
| |
| // export const useLocalStorage = <T>(key: string): T | null => { |
| // const [value, setValue] = useState<T | null>(null); |
| |
| // useEffect(() => { |
| // if (typeof window !== 'undefined') { |
| // const item = localStorage.getItem(key); |
| // if (item) { |
| // try { |
| // setValue(JSON.parse(item)); |
| // console.log(JSON.parse(item)); |
| // } catch (e) { |
| // console.error(`解析 localStorage ${key} 失败`, e); |
| // } |
| // } |
| // } |
| // }, [key]); |
| |
| // return value; |
| // }; |
| |
| export const useLocalStorage = <T>(key: string): T | null => { |
| const isClient = typeof window !== 'undefined'; |
| const [value, setValue] = useState<T | null>(() => { |
| if (isClient) { |
| const item = localStorage.getItem(key); |
| if (item) { |
| try { |
| return JSON.parse(item); |
| } catch (e) { |
| console.error(`解析 localStorage ${key} 失败`, e); |
| } |
| } |
| } |
| return null; |
| }); |
| |
| useEffect(() => { |
| if (!isClient) return; |
| const item = localStorage.getItem(key); |
| if (item) { |
| try { |
| setValue(JSON.parse(item)); |
| } catch (e) { |
| console.error(`解析 localStorage ${key} 失败`, e); |
| } |
| } |
| }, [key]); |
| |
| return value; |
| }; |