LocalStorage 不会在刷新时保存

LocalStorage doesn't save on refresh

它在我提交时显示 localStorage 中的数据,但在刷新时它会清除 LocalStorage。

我错过了什么?

上下文:这是一个简单的 todo 应用程序,App 组件是唯一一个包含 localStorage 或 useEffect 的组件。

来自 Youtube 上 Dev Ed 的教程“使用 REACT 构建 Todo 应用程序”

import "./App.css";
import { useState,useEffect } from "react";
import Form from "./components/Form/Form";
import TodoList from "./components/TodoList/TodoList";

function App() {


  const [inputText, setInputText] =  useState("")
  const [todos, setTodos] = useState([])
  const [status, setStatus] = useState("all")
  const [filteredTodos, setFilteredTodos] = useState([])

  useEffect(() => {
    filterHandler()
    saveLocalTodos()
  },[todos, status])

  useEffect(() => {
    getLocalTodos()
  },[])


  const filterHandler = () => {
    switch(status){
      case "completed":
        setFilteredTodos(todos.filter(todo => todo.completed === true))
        break;
      case "uncompleted":
        setFilteredTodos(todos.filter(todo => todo.completed ===false))
        break;
      default:
        setFilteredTodos(todos)
        break;
    }
  }

  const saveLocalTodos = () => {
      localStorage.setItem("todos", JSON.stringify(todos))
  }

  const getLocalTodos = () => {
    if(localStorage.getItem("todos") === null){
      localStorage.setItem("todos", JSON.stringify([]));
    }else {
      let todoLocal = JSON.parse(localStorage.getItem("todos"));
      setTodos(todoLocal)
    }
  }


  return <div className="App">
    
    <header>
      <h1>Todo - List</h1>
      <Form 
      todos={todos} 
      setTodos={setTodos} 
      inputText={inputText} 
      setInputText={setInputText}
      setStatus={setStatus}
     
      />
      <TodoList  filteredTodos={filteredTodos}  setTodos={setTodos} todos={todos}/>
    </header>
    
    
    </div>;
}

export default App;

保存到localStorage前需要检查待办事项是否为空

useEffect(() => {
    filterHandler()
if(todos.length !== 0)
    saveLocalTodos()
  },[todos, status])

这对我有用(感谢 Lah Ezcen 和 Jax-p):

    const saveLocalTodos = () => {
    if(todos.length !== 0){        //this line is new
      localStorage.setItem("todos", JSON.stringify(todos))
    }   
    }

它现在检查数组是否为空,如果不是则保存到 localStorage。