localStorage 刷新后为空

huangapple go评论65阅读模式
英文:

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.

localstorage

答案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]);

huangapple
  • 本文由 发表于 2023年3月31日 03:43:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定