无法从本地存储检索数据



我试图在这个react应用程序的localStorage中保存联系人。

import "./App.css";
import "bootstrap/dist/css/bootstrap.css";
import Header from "./Header";
import AddContact from "./AddContact";
// import ContactCard from './ContactCard'
import ContactList from "./ContactList";
import { useEffect, useState } from "react";
function App() {
const LOCAL_STORAGE_KEY = "contacts";
const [contacts, setContacts] = useState([]);
const addContactHandler = (contact) => {
setContacts([...contacts, contact]);
};
useEffect(() => {
console.log("Saving contacts:", contacts);
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
console.log("Retrieved contacts:", retriveContacts);
if (retriveContacts) setContacts(retriveContacts);
}, []);
return (
<div className="container">
<Header />
<AddContact AddContactHandler={addContactHandler} />
<ContactList contacts={contacts} />
</div>
);
}
export default App;

当我添加联系人时,它被保存到localstorage,但每当我刷新页面时,localstorage被清空。

当我这样做的时候,我发现

import "./App.css";
import "bootstrap/dist/css/bootstrap.css";
import Header from "./Header";
import AddContact from "./AddContact";
// import ContactCard from './ContactCard'
import ContactList from "./ContactList";
import { useEffect, useState } from "react";
function App() {
const LOCAL_STORAGE_KEY = "contacts";
const [contacts, setContacts] = useState([]);
const addContactHandler = (contact) => {
setContacts([...contacts, contact]);
localStorage.setItem(
LOCAL_STORAGE_KEY,
JSON.stringify([...contacts, contact])
);
};
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (retriveContacts) setContacts(retriveContacts);
}, []);
return (
<div className="container">
<Header />
<AddContact AddContactHandler={addContactHandler} />
<ContactList contacts={contacts} />
</div>
);
}
export default App;

您可以将联系人保存在事件中,也可以在使用状态下直接加载联系人,像这样

const [contacts, setContacts] = useState(() => {
const retrieveContacts = localStorage.getItem(LOCAL_STORAGE_KEY);
return retrieveContacts ? JSON.parse(retrieveContacts) : [];
});
const addContactHandler = (contact) => {
const newContacts = [...contacts, contact];
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newContacts));
setContacts(newContacts);
};

,你可以删除useEffects,这些是不必要的,并防止任何副作用

相关内容

  • 没有找到相关文章

最新更新