英文:
localStorage empty after refresh
问题
我需要在nextjs
中使用localStorage
,但在刷新后我失去了所有数据(控制台中为空数组[])。 这是我尝试的:
const [todos, setTodos] = useState([]);
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem('todos')) || [];
setTodos(storedTodos);
}, []);
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [todos]);
这在React
中有效:
const [todos, setTodos] = useState(
() => JSON.parse(localStorage.getItem('todos')) || []
);
但在nextjs
中我看到localstorage is not defined
。
谢谢!
英文:
I need to use localStorage
in nextjs
but after refresh i lose all the data (empty array [] in the console).
this is what i tried:
const [todos, setTodos] = useState([]);
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem('todos')) || [];
setTodos(storedTodos);
}, []);
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [todos]);
This works in React
:
const [todos, setTodos] = useState(
() => JSON.parse(localStorage.getItem('todos')) || []
);
but in nextjs
i see localstorage is not defined
.
Thank you!
答案1
得分: 0
尝试只使用 localStorage.setItem('todos', "test");
,不使用 useEffect,并检查浏览器是否已在本地存储中保存它。
请确保你是在类组件或函数组件中设置它。
英文:
Try just localStorage.setItem('todos', "test");
without useEffect and check your whether your browser has saved it in local storage.
Please also make sure you're setting it in a class/function component.
答案2
得分: 0
useEffect
会在每次刷新时重置 localStorage
,所以我添加了 todos.length === 0
来检查:
const [todos, setTodos] = useState([]);
if (typeof window !== 'undefined') {
if (localStorage.getItem('todos') === null) {
localStorage.setItem('todos', JSON.stringify([])); // 在此初始化以防止在 useeffect (todos.length) 中出现空指针
}
}
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem('todos'));
setTodos(storedTodos);
}, []);
useEffect(() => {
if (todos.length === 0) {
console.log("数组为空!")
} else {
localStorage.setItem('todos', JSON.stringify(todos));
}
}, [todos]);
英文:
the useEffect
was resetting the localStorage
every refresh, so i added todos.length === 0
to check:
const [todos, setTodos] = useState([]);
if (typeof window !== 'undefined') {
if ((localStorage.getItem('todos')) === null) {
localStorage.setItem('todos', JSON.stringify([])); // initialize here to prevent the null pointer in useeffect (todos.length)
}
}
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem('todos'));
setTodos(storedTodos);
}, []);
useEffect(() => {
if (todos.length === 0) {
console.log("Array is empty!")
} else {
localStorage.setItem('todos', JSON.stringify(todos));
}
}, [todos]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论