简体   繁体   English

React App 刷新后不将数据存储到本地存储

[英]React App doesnt store data to local storage after refresh

My react app will save data to local storage but when refreshed the data disappears.我的 React 应用程序会将数据保存到本地存储,但刷新后数据会消失。 What am I doing wrong with local storage?我在本地存储上做错了什么?

    import { useEffect, useState } from "react";
    import { nanoid } from "nanoid";
    import NoteList from "./components/noteList";
    import Search from "./components/search";
    import Header from "./components/header";

const App = () => {
  const [notes, setNotes] = useState([]);

  const [searchText, setSearchText] = useState("");

  useEffect(() => {
    const savedNotes = JSON.parse(localStorage.getItem("notes-data"));

    if (savedNotes) {
      setNotes(savedNotes);
    }
  }, []);

  useEffect(() => {
    localStorage.setItem("notes-data", JSON.stringify(notes));
  }, [notes]);

  const addNote = (text) => {
    const date = new Date();
    const newNote = {
      id: nanoid(),
      text: text,
      date: date.toLocaleDateString(),
    };
    const newNotes = [...notes, newNote];
    setNotes(newNotes);
  };

  const deleteNote = (id) => {
    const newNotes = notes.filter((note) => note.id !== id);
    setNotes(newNotes);
  };

  return (
    <div>
      <div className="container">
        <Header />
        <Search handleSearchNote={setSearchText} />
        <NoteList
          notes={notes.filter((note) =>
            note.text.toLowerCase().includes(searchText)
          )}
          handleAddNote={addNote}
          handleDeleteNote={deleteNote}
        />
      </div>
    </div>
  );
};

export default App;

From everything that I have read I can't see what I'm doing wrong unless its something simple.从我读过的所有内容中,除非它很简单,否则我看不出我做错了什么。

This is pre refresh这是刷新前

this is post refresh这是刷新后

The problem is in the second useEffect hook since it is executing depending on notes array (initially is empty), this causes the localstorage data to be "erased" (in reality it is updated to an empty array after component mounts).问题出在第二个useEffect挂钩中,因为它是根据notes数组执行的(最初是空的),这会导致本地存储数据被“擦除”(实际上它会在组件挂载后更新为空数组)。

To understand better what I mean add a console log here to see when it is executing and what data is saved.为了更好地理解我的意思,请在此处添加控制台日志以查看它何时执行以及保存了哪些数据。

useEffect(() => {
console.log('saving data to local storage', notes);

localStorage.setItem("notes-data", JSON.stringify(notes));
}, [notes]);

Update:更新:

You can handle that by stoping the useEffect execution on first render (for more information check this question )您可以通过在第一次渲染时停止执行useEffect来处理这个问题(有关更多信息,请查看此问题

That is because of this code snippet useEffect(() => { localStorage.setItem("notes-data", JSON.stringify(notes)); }, [notes]);这是因为这个代码片段useEffect(() => { localStorage.setItem("notes-data", JSON.stringify(notes)); }, [notes]);

Before setting notes-data please check if the localStorage has notes-data already set using localStorage.getItem("notes-data") in an if condition.在设置 notes-data 之前,请检查 localStorage 是否已经在 if 条件下使用localStorage.getItem("notes-data")设置了 notes-data。

it's because your react Component is rendering twice and to solve this issue you have to disable the <React.StrictMode> in your index.js file:- For example, you might find that your is wrapped by <React.StrictMode> in your index.js:这是因为你的反应组件渲染了两次,为了解决这个问题,你必须在你的 index.js 文件中禁用 <React.StrictMode> :- 例如,你可能会发现你的索引被 <React.StrictMode> 包裹.js:

 ReactDOM.render(
     <React.StrictMode>
       <App />
     </React.StrictMode>,
  );

If so, you can disable StrictMode by removing the <React.StrictMode> tag:如果是这样,您可以通过删除 <React.StrictMode> 标签来禁用 StrictMode:

ReactDOM.render(
    <App />
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM