曹耘豪的博客

Nextjs localStorage is not defined

仅仅在文件头增加'use client'是不行的,还要使用useEffect

1
2
3
4
5
6
7
const [value, setValue] = useState<T>(initValue);
useEffect(() => {
let stored = localStorage.getItem(key)
if (stored !== null) {
setValue(stored);
}
}, []);

如果通过typeof window判断,如下,虽然可以编译通过,但初始化的值并不是localStorage的值

1
2
3
4
5
6
7
8
9
10
11
const [value, setValue] = useState<T>(() => {
let stored = null
if (typeof window !== 'undefined') {
stored = localStorage.getItem(key)
}

if (stored !== null) {
return stored;
}
return initValue
});
   / 
  ,