javascript 当我重新加载我的react应用程序时,状态中的更改会被重新加载,但是我使用了钩子来管理localStorage

hfsqlsce  于 8个月前  发布在  Java
关注(0)|答案(1)|浏览(38)

我在这里使用了useEffect(),但是当我检查本地存储时,显示的长度为零,但是我正确地使用了react钩子。我在我的todolist应用程序中创建了一个单独的文件来管理上面提到的代码的localstorage。

const getLocalStorage = () => {
  let todos = localStorage.getItem("todos");
  if (todos) {
    return (list = JSON.parse(localStorage.getItem("todos")))
  } else {
    return [];
  }
};

export const TodoWrapperLocalStorage = () => {
  const [todos, setTodos] = useState(getLocalStorage());
  useEffect(() => {
    if (todos.length > 0 && todos != null) {
      localStorage.setItem('todos', JSON.stringify(todos))
    }
  }, [todos]);
}
oalqel3c

oalqel3c1#

here is the solution you looking for,
In your useEffect, you're checking if todos.length > 0 && todos != null 
before saving to local storage. The problem here is that 
localStorage.setItem is synchronous, and it doesn't return any errors if it 
fails. So, it might be a better practice to directly stringify and save the 
todos without the if condition like this:

export const TodoWrapperLocalStorage = () => {
  const [todos, setTodos] = useState(getLocalStorage());

  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
  }, [todos]);

}

相关问题