LocalStorage过期日期在午夜之后使用时刻



我正在努力与我的应用程序上的localStorage到期日期。问题在这里:

当用户单击按钮时,我在本地存储中设置了一个变量。在这个按钮被点击后,我不希望它在一天的午夜之后再次显示,例如,如果我点击20:00的按钮,我希望它不会再显示4个小时。

我有这个函数,由redux saga触发:

const setVarReservation = (key, value, ttl) => {
window.localStorage.setItem('alertToBeSetted', moment().format('YYYY-MM-DD'));
};

所以我的变量将有key: alerttobeset, value: today date.

我每次登录应用程序时都调用一个saga,所以我可以很容易地在这里进行检查。我想实现的是:

const isVarClicked = window.localStorage.getItem('alertToBeSetted');
if (isVarClicked > midnightOfThisDay) {
window.localStorage.removeItem(alertReservationVar);
}

有可能实现这个使用时刻吗?如果没有,谁能给我一个有效的解决方案?

Thanks in advance

如果您将存储中的今天日期设置为值,我认为当您给isVarClicked一个值时,您应该检查它是否等于今天的日期。

// `isVariable` are usually used for boolean data.
// so here you can assing a condition like this
// to check if the button was pressed today
const isVarClickedToday = localStorage.getItem('alertToBeSetted') === moment().format('YYYY-MM-DD');
if (isVarClickedToday) {
// Hide Button
} else {
// Show Button
if (localStorage.getItem('alertToBeSetted')) { // True with a date, false without a value stored. (for js implicit boolean conversion)
// If the button wasn't clicked today, but we have something in the storage, we removing it (cause it's not about today)
localStorage.removeItem('alertToBeSetted');
}
}

这样,当日期与今天匹配时,您只需隐藏按钮,当日期不匹配时,显示按钮并重置localStorage(如果存在)。

希望这对你有帮助:)

最新更新