gpt4 book ai didi

reactjs - localStorage 正在保存我的数据,但在刷新后重置并清空它

转载 作者:行者123 更新时间:2023-12-05 02:30:06 26 4
gpt4 key购买 nike

我有一个问题,我需要你帮助我理解它。我正在使用 ReactJS 并且正在构建一个简单的 CRUD Todo 应用程序。我想将我的待办事项存储在本地存储中。数据保存在那里,我可以看到它,但刷新后它清空了我的本地存储。

我做错了什么?我注意到的一点是,从我第一次打开应用程序(第一次渲染)开始,本地存储正在创建存储空间而不添加待办事项。

我的代码中是否遗漏了一些东西,导致它在呈现页面时重置或清空它?

import React, { useState, useEffect } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faCheck,
faPen,
faPlus,
faTrashCan,
} from "@fortawesome/free-solid-svg-icons";
import "./App.css";
import { faCircleCheck } from "@fortawesome/free-regular-svg-icons";

function App() {
const [todos, setTodos] = useState([]);
const [todo, setTodo] = useState("");

const [todoEditing, setTodoEditing] = useState(null);
const [editingText, setEditingText] = useState("");

useEffect(() => {
const json = window.localStorage.getItem("todos");
const loadedTodos = JSON.parse(json);
if (loadedTodos) {
setTodos(loadedTodos);
}
}, []);

useEffect(() => {
const json = JSON.stringify(todos);
window.localStorage.setItem("todos", json);
}, [todos]);

function handleSubmit(e) {
e.preventDefault();

const newTodo = {
id: new Date().getTime(),
text: todo,
completed: false,
};

setTodos([...todos].concat(newTodo));
setTodo("");
}

function deleteTodo(id) {
const updatedTodos = [...todos].filter((todo) => todo.id !== id);
setTodos(updatedTodos);
}

function toggleComplete(id) {
let updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.completed = !todo.completed;
}
return todo;
});
setTodos(updatedTodos);
}

function submitEdits(id) {
const updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.text = editingText;
}
return todo;
});
setTodos(updatedTodos);
setTodoEditing(null);
}

return (
<div className="App">
<div className="app-container">
<div className="todo-header">
<form onSubmit={handleSubmit}>
<input
type="text"
name="todo-input-text"
placeholder="write a todo..."
onChange={(e) => {
setTodo(e.target.value);
}}
value={todo}
/>
<button>
<FontAwesomeIcon icon={faPlus} />
</button>
</form>
</div>
<div className="todo-body">
{todos.map((todo) => {
return (
<div className="todo-wrapper" key={todo.id}>
{todo.id === todoEditing ? (
<input
className="edited-todo"
type="text"
onChange={(e) => setEditingText(e.target.value)}
/>
) : (
<p className={todo.completed ? "completed" : "uncompleted"}>
{todo.text}
</p>
)}
<div className="todo-buttons-wrapper">
<button onClick={() => toggleComplete(todo.id)}>
<FontAwesomeIcon icon={faCircleCheck} />
</button>
{todo.id === todoEditing ? (
<button onClick={() => submitEdits(todo.id)}>
<FontAwesomeIcon icon={faCheck} />
</button>
) : (
<button onClick={() => setTodoEditing(todo.id)}>
<FontAwesomeIcon icon={faPen} />
</button>
)}
<button
onClick={() => {
deleteTodo(todo.id);
}}
>
<FontAwesomeIcon icon={faTrashCan} />
</button>
</div>
</div>
);
})}
</div>
</div>
</div>
);
}

export default App;

from the first render is allocating the space

after I add a todo ass you can see is saving it to my local storage but after the refresh is empty just like in the first image

最佳答案

如果像这样在 localStorage 中可用,您应该从 localStorage 加载 todos 到组件挂载上,

const loadedTodos = localStorage.getItem("todos")
? JSON.parse(localStorage.getItem("todos"))
: []; // new

const [todos, setTodos] = useState(loadedTodos); // updated

然后您不必在 useEffect 中使用 setTodos(loadedTodos) 来改变状态。

只需从代码中删除这个 useEffect :

// that useEffect should be removed
useEffect(() => {
const json = window.localStorage.getItem("todos");
const loadedTodos = JSON.parse(json);
if (loadedTodos) {
setTodos(loadedTodos);
}
}, []);

您可以在工作中查看 CodeSandbox

关于reactjs - localStorage 正在保存我的数据,但在刷新后重置并清空它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71961041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com