问题描述:
我正在编写一个简单的待办事项应用程序并尝试将数据保存在本地存储中。我看过几个考虑在 React 中使用 localStorage 的教程,并按照他们说的一步一步做,代码似乎还不错。似乎是问题所在,是本地存储本身。当我使用 localStorage.setItem() 添加待办事项时,它应该会自动更新并显示数据,但事实并非如此。只有当我刷新它(应用程序 - > 本地存储中控制台中带有键值对的字段上方的小刷新按钮)时,我才能看到显示的键值对,所以看起来它已经工作了。但是,即使手动刷新后似乎保留了数据,但当我刷新整个页面时,数据消失了。下面我包含了我的分代码:
- const [todos, setTodos] = useState([]);
-
- const addTodo = (e) => {
- e.preventDefault();
- if (inputValue.trim() === "") return;
- setTodos([
- ...todos,
- {
- text: inputValue,
- id: uuidv4(),
- },
- ]);
-
- setInputValue("");
- };
-
- useEffect(() => {
- const localData = localStorage.getItem("TODO_APP");
- if (localData !== null) setTodos(JSON.parse(localData));
- }, []);
-
- useEffect(() => {
- localStorage.setItem("TODO_APP", JSON.stringify(todos));
- }, [todos]);
解决思路一:
我将添加另一个稍作修改的版本。应该管用:
- const [todos, setTodos] = useState(JSON.parse(localStorage.getItem('TODO_APP')) || []);
-
- const addTodo = (e) => {
- e.preventDefault();
-
- if (inputValue.trim() !== '') {
- setTodos([
- ...todos,
- {
- text: inputValue,
- id: uuidv4()
- }
- ]);
- }
-
- setInputValue('');
- };
-
- useEffect(() => {
- localStorage.setItem('TODO_APP', JSON.stringify(todos));
- }, [todos]);
解决思路二:
其他解决方案可能对您有用,但如果您正在使用React 18,您的代码非常好,问题是useEffects在刷新时调用了两次,它正在重置 localStorage。这是一种已知问题。
您只需要StrictMode在src/index.js文件中禁用index.js
- import React from "react";
- import ReactDOM from "react-dom/client";
- import "./index.css";
- import App from "./App";
- import reportWebVitals from "./reportWebVitals";
-
- const root = ReactDOM.createRoot(document.getElementById("root"));
- root.render(<App />);
-
- reportWebVitals();
我尝试完成组件的缺失部分,最终组件如下所示:
- import { useState, useEffect } from "react";
-
- const Todo = () => {
- const [todos, setTodos] = useState([]);
- const [inputValue, setInputValue] = useState("");
-
- const onChangeHandler = (e) => {
- setInputValue(e.target.value);
- };
-
- const addTodo = (e) => {
- e.preventDefault();
- if (inputValue.trim() === "") return;
- setTodos([...todos, { text: inputValue }]);
-
- setInputValue("");
- };
-
- useEffect(() => {
- console.log("1st");
- const localData = localStorage.getItem("TODO_APP");
- console.log(localData);
- if (localData.length !== 0) setTodos(JSON.parse(localData));
- }, []);
-
- useEffect(() => {
- console.log("2nd");
- localStorage.setItem("TODO_APP", JSON.stringify(todos));
- }, [todos]);
-
- return (
- <form onSubmit={addTodo}>
- <input type="text" value={inputValue} onChange={onChangeHandler}>input>
- <button type="submit">ADD TODObutton>
- form>
- );
- };
-
- export default Todo;
我console.log()在代码中添加了 sso 你可以观察它们useEffects是如何在刷新时调用的
解决思路三(这是解决小编问题的思路):
以上仅为部分解决思路,添加下方公众号后回复001,即可查看全部内容。公众号有许多评分最高的编程书籍和其它实用工具,无套路,可放心使用
如果您觉得有帮助,可以关注公众号——立志于成为对程序员有益的公众号