我想将默认数据(几个对象)插入本地存储并在第一次渲染时将其加载到屏幕上。
const getLocalStorage = JSON.parse(localStorage.getItem('Data'))
const [todos, setTodos] = useState(getLocalStorage ? getLocalStorage : []);
useEffect(() => {
localStorage.setItem("Data", JSON.stringify(todos)); //set item in localstorage
}, [todos])
这是待办事项的示例:
{ id: Math.floor(Math.random() * 10000), task: 'todo here', completed: false, isEditing: false, date: date }
我尝试将数据添加到待办事项中,但每次渲染时都会重新添加。使用 useEffect 将其添加到本地存储时也不起作用。
如果您想要某种正确的方法来将状态持久保存到 localStorage,请执行以下操作:
hooks/localStorage.jsx
import React from "react";
function dispatchStorageEvent(key, newValue) {
window.dispatchEvent(new StorageEvent("storage", { key, newValue }));
}
const getLocalStorageItem = (key) => {
return window.localStorage.getItem(key);
};
const useLocalStorageSubscribe = (callback) => {
window.addEventListener("storage", callback);
return () => window.removeEventListener("storage", callback);
};
const removeLocalStorageItem = (key) => {
window.localStorage.removeItem(key);
dispatchStorageEvent(key, null);
};
const setLocalStorageItem = (key, value) => {
const stringifiedValue = JSON.stringify(value);
window.localStorage.setItem(key, stringifiedValue);
dispatchStorageEvent(key, stringifiedValue);
};
export function useLocalStorage(key, initialValue) {
const getSnapshot = () => getLocalStorageItem(key);
const store = React.useSyncExternalStore(
useLocalStorageSubscribe,
getSnapshot
);
const setState = React.useCallback(
(v) => {
try {
const nextState = typeof v === "function" ? v(JSON.parse(store)) : v;
if (nextState === undefined || nextState === null) {
removeLocalStorageItem(key);
} else {
setLocalStorageItem(key, nextState);
}
} catch (e) {
console.warn(e);
}
},
[key, store]
);
React.useEffect(() => {
if (
getLocalStorageItem(key) === null &&
typeof initialValue !== "undefined"
) {
setLocalStorageItem(key, initialValue);
}
}, [key, initialValue]);
return [store ? JSON.parse(store) : initialValue, setState];
}
您可以按以下方式使用它:
// import
import { useLocalStorage } from "./hooks/localStorage";
// use
const [todos, setTodos] = useLocalStorage('Data', []); // you can use your initial value in place of [] here