1 回答
TA贡献1911条经验 获得超7个赞
这实际上取决于您要存储的数据量。通常,当您需要处理少量数据时,您更喜欢使用 localStorage。
另一种选择也是可能的,它是 IndexedDB,它更兼容并且允许您存储更多数据。
但是如果你想窃取使用 localStorage,那么你可以在获取数据之前检查是否使用了密钥存储“数据”:
const data = localStorage.getItem('data');
if (!data) {
// then fetch your data
}
请注意,localStorage 始终存储键值对,并且值始终是字符串。因此,如果您想在检索值时处理它,请不要忘记JSON.parse(data)
编辑:重新打开选项卡时刷新过时的数据
要每 3-4 小时更新一次数据,您可以存储获取数据的日期。您需要更新一点,但对承诺结果中的响应的处理:
const getDataFromLocalStorage = () => {
const dataStringified = localStorage.getItem('data');
return data && JSON.parse(dataStringified) || null;
};
const areDataOutdated = (receivedAt) => {
if (!dataReceivedAt || isNaN(Date.parse(receivedAt)) {
return true;
}
// Basically, we take the actual date, and we removed 4 hours
const checkDate = new Date(new Date().getTime() - (60 * 60 * 4 * 1000));
// If the data received is lower than the checkDate, it means that data are outdated.
return new Date(receivedAt).getTime() < checkDate.getTime();
};
const data = getDataFromLocalStorage();
if (!data || areDataOutdated(data && data.receivedAt)) {
// then fetch your data
fetch("https://coronavirus-tracker-api.herokuapp.com/deaths")
.then(res=> {
// instead of storing directly your response, construct a object that will store also the date
localStorage.setItem("data", JSON.stringify({response: res.json(), receivedAt: new Date()}));
console.log(localStorage.getItem("data"))
})
}
编辑2:停留在页面上时刷新数据
const getDataFromLocalStorage = () => {
const dataStringified = localStorage.getItem('data');
return data && JSON.parse(dataStringified) || null;
};
const fetchData = () => {
fetch("https://coronavirus-tracker-api.herokuapp.com/deaths")
.then(res=> {
// instead of storing directly your response, construct a object that will store also the date
localStorage.setItem("data", JSON.stringify({response: res.json(), receivedAt: new Date()}));
console.log(localStorage.getItem("data"))
})
}
setInterval(() => {
fetchData();
}, 1000 * 60 * 60 * 4) // every 4 hours, we'll fetch the data.
const data = getDataFromLocalStorage();
if (!data) {
fetchData();
}
但您也可以结合编辑 1 中的过时数据检查。
- 1 回答
- 0 关注
- 92 浏览
添加回答
举报