我对如何使用localStorage持久保存来自调用API的数据感到困惑。 我希望每当刷新页面时,useEffect内的callApi都不会呈现新数据并保持现有数据不变。
任何帮助将不胜感激。
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Layout, Loading, OverviewHeader, OverviewSubHeader, SiteCard } from '../components';
const Overview = () => {
const [loading, setLoading] = useState(true);
const [sites, setSites] = useState([]);
useEffect(() => {
async function callApi() {
const response = await axios.get(`https://randomuser.me/api/?results=3`);
const sites = response?.data?.results;
console.log('sites', sites);
setSites(sites);
await localStorage.setItem('sites', JSON.stringify(sites));
setLoading(false);
}
callApi();
}, []);
return (
<div>
<Layout>
<OverviewHeader />
<OverviewSubHeader />
<div className='overview-page-wrapper'>
{loading ? (
<Loading />
) : (
sites.map(site => {
return (
<React.Fragment>
<SiteCard
key={site.login.uuid}
siteId={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
notifications={site.registered.age}
latitude={site.location.coordinates.latitude}
longitude={site.location.coordinates.longitude}
{...site}
/>
</React.Fragment>
);
})
)}
</div>
</Layout>
</div>
);
};
export default Overview;
答案 0 :(得分:1)
我不太确定您要完成什么,因为您可能想在某个时候刷新该数据。 也许您可以指出要尝试的行为/场景?
无论如何,要回答您的问题,您可以做的是这样:
const [displayedSites, setDisplayedSites] = useState([])
// this does both setting the state for your UI
// and stores to localStorage
const setAndSaveDisplayedSites = (fetchedSites) => {
setDisplayedSites(sites)
localStorage.setItem('sites', JSON.stringify(sites))
}
useEffect(() => {
(async function () {
const localSites = localStorage.getItem(sites);
if (!localSites) {
// this will only ever fetch if it is your first time mounting this component
// I suppose you would need to call setAndSaveDisplayedSites
// from a "refresh" button
const fetchedSites = await getSitesFromAPI()
setAndSaveDisplayedSites(fetchedSites)
return
}
const parsedLocalSites = JSON.parse(localSites)
setDisplayedSites(parsedLocalSites)
})()
}, [])
还要签出此挂钩,它可以为您处理一些事情:https://usehooks.com/useLocalStorage/
答案 1 :(得分:0)
为此使用useContext挂钩,或者如果您确实只是想以任何方式使用本地存储,则可以使用它,但要为此管理不同的状态/变量。
希望这是有道理的。谢谢!