next.js 刷新后localStorage为空

6l7fqoea  于 2023-04-05  发布在  其他
关注(0)|答案(2)|浏览(195)

我需要在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
谢谢你!

aurhwmvo

aurhwmvo1#

只尝试localStorage.setItem('todos', "test");而不使用useEffect,并检查您的浏览器是否已将其保存在本地存储中。
请确保你是在一个类/函数组件中设置的。
localstorage

k10s72fa

k10s72fa2#

useEffect每次刷新都重置localStorage,所以我添加了todos.length === 0来检查:

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

相关问题