[英]How to store multiple set of data in local storage in reactjs?
我有一個名為“Post.js”的頁面,我想在其中單擊“添加收藏夾”按鈕並將數據保存到本地存儲中。 但是在每次新的點擊中,數據都會被前一次替換,而不是添加新數據。
這是“Post.js” :
const Posts = ({ posts, loading }) => {
const click = (id, name, bio, link) => {
//setButtonText(text);
const obj = {
id: id,
name: name,
bio: bio,
link: link,
};
localStorage.setItem('items', JSON.stringify({ ...obj }));
};
if (loading) {
return <h2>Loading...</h2>;
}
return (
<div className="fav-content">
<ul className="card">
{posts.map((item, index) => {
console.log(item._id);
return (
<li key={item._id}>
<button
onClick={() => click(item._id, item.name, item.bio, item.link)}
>
Add Favt
</button>
<Card style={{ width: '18rem' }}>
<Card.Body>
<Card.Title>Name: {item.name}</Card.Title>
<Card.Text>Bio: {item.bio}</Card.Text>
<Card.Text>Link: {item.link}</Card.Text>
</Card.Body>
</Card>
</li>
);
})}
</ul>
</div>
);
};
我想將那些保存的數據從本地存儲中提取到“Favauth”文件中。
這是“Favauth.js” :
function FavAuthor() {
const [data, setItems] = useState([]);
useEffect(() => {
const localStorageItems = JSON.parse(localStorage.getItem('items'));
console.log(localStorageItems);
if (localStorageItems) {
setItems(localStorageItems);
}
}, []);
return (
<>
<div className="fav-content">
<ul className="card">
<li key={data.id}>
<Card style={{ width: '18rem' }}>
<Card.Body>
<Card.Title>Name: {data.name}</Card.Title>
<Card.Text>Bio: {data.bio}</Card.Text>
<Card.Text>Link: {data.link}</Card.Text>
</Card.Body>
</Card>
</li>
</ul>
</div>
</>
);
}
您正在替換數據而不是將其附加到現有數據。 您應該首先檢索舊數據。 然后合並新舊數據,然后將其保存在posts.js
的localStorage
中。
let oldData = JSON.parse(localStorage.getItem('items'))
localStorage.setItem('items', JSON.stringify([ ...oldData, ...obj ]));
然后在FavAuth.js
中,您應該循環遍歷localStorage
中的項目。
...
{data.map(post => (
<li key={post.id}>
<Card style={{ width: '18rem' }}>
<Card.Body>
<Card.Title>Name: {post.name}</Card.Title>
<Card.Text>Bio: {post.bio}</Card.Text>
<Card.Text>Link: {post.link}</Card.Text>
</Card.Body>
</Card>
</li>
))
}
...
這是關於渲染的問題。 試試這個鈎子以呈現最新的 localStorage 數據而不是以前的數據: https://usehooks.com/useLocalStorage/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.