我有以下自定义挂钩,它将数据存储在本地存储中:
import { useCallback, useEffect, useState } from "react";
export const useLocalStorage = (key, initialValue) => {
const initialize = (key) => {
try {
const item = localStorage.getItem(key);
if (item && item !== "undefined") {
return JSON.parse(item);
}
localStorage.setItem(key, JSON.stringify(initialValue));
return initialValue;
} catch {
return initialValue;
}
};
const [state, setState] = useState(() => initialize(key)); // problem is here
const setValue = useCallback(
(value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setState(valueToStore);
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
},
[key, setState]
);
const remove = useCallback(() => {
try {
localStorage.removeItem(key);
} catch {
console.log(error);
}
}, [key]);
return [state, setValue, remove];
};
它显示了以下问题,我用谷歌搜索了它,似乎是由于 Nextjs 尝试在服务器端运行代码并且没有可用的窗口对象所致。
问题似乎来自我尝试初始化存储数据的行:
const [state, setState] = useState(() => initialize(key));
我尝试将此逻辑打包在 useEffect 中,以便它仅在客户端运行,但我遇到了无法解决的无限循环。
import { useCallback, useEffect, useState } from "react";
export const useLocalStorage = (key, initialValue) => {
const initialize = (key) => {
try {
const item = localStorage.getItem(key);
if (item && item !== "undefined") {
return JSON.parse(item);
}
localStorage.setItem(key, JSON.stringify(initialValue));
return initialValue;
} catch {
return initialValue;
}
};
const [state, setState] = useState(null); // problem is here
// solution is here....
useEffect(()=>{
setState(initialize(key));
},[]);
const setValue = useCallback(
(value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setState(valueToStore);
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
},
[key, setState]
);
const remove = useCallback(() => {
try {
localStorage.removeItem(key);
} catch {
console.log(error);
}
}, [key]);
return [state, setValue, remove];
};
window,localStorage,sessionStorage,etc..
未在服务器上定义,因此在服务器上访问它们将导致错误。使用useEffect
为了确保这一点,这些代码将在客户端执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)