# 如何设置一个支持过期时间的 localStorage
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 571 (opens new window)
Author
function initLocalStorage() {
localStorage.setItem = function (key, value, time = 1000) {
const expiresTime = Date.now() + time * 1000;
const payload = {
__data: value,
__expiresTime: expiresTime,
};
Storage.prototype.setItem.call(localStorage, key, JSON.stringify(payload));
};
localStorage.getItem = function (key) {
const value = Storage.prototype.getItem.call(localStorage, key);
if (typeof value === "string") {
const jsonVal = JSON.parse(value);
if (jsonVal.__expiresTime) {
if (jsonVal.__expiresTime >= Date.now()) {
return JSON.stringify(jsonVal.__data);
} else {
return null;
}
}
}
return value;
};
}
initLocalStorage();
想了下 只能去改 api 去封装一层 不过存在一个问题就是别人在使用的时候 也需要遵循这个规则 没想到别的办法