为什么要做带过期时间的储存?
localStorage允许我们在浏览器中存储数据,并且这些数据在页面重新加载或关闭后仍然保存。做项目开发时,我们有时可能会需要数据的定时存储(例如用户登录后token的有效时间),但是localStorage不支持直接存储带有过期时间的数据,所以这也是它的一大弊端。在这篇博客中,我将通过编写两个简单的函数来实现localStorage的定时存储。
实现思路:
为了实现带过期时间的存储,我们可以创建一个对象,该对象要包含:要存储的值和该值的过期时间。然后,我们将这个对象转换为JSON字符串,并存储在localStorage中。当我们需要获取该值时,首先要检查其过期时间,看看是否已经过期,如果已过期,则删除该值并返回null。否则,我们返回存储的值。
实现代码:
// 设置带有过期时间的键值对到localStorage中
function setLocalStorageWithExpire(key, value, expireTime) {
// 获取当前时间的时间戳
const now = new Date().getTime();
const expires = now + expireTime;
// 计算过期时间的时间戳
const item = {
value: value,
// 存储过期时间
expires: expires
};
// 将对象转换为JSON字符串并存储
localStorage.setItem(key, JSON.stringify(item));
}
// 从localStorage中获取带有过期时间的键值对
function getLocalStorageWithExpire(key) {
// 从localStorage中获取JSON字符串
const itemStr = localStorage.getItem(key);
// 如果不存在,返回null
if (!itemStr) {
return null;
}
// 将JSON字符串解析为对象
const item = JSON.parse(itemStr);
// 获取当前时间的时间戳,并与储存的过期时间戳进行对比
const now = new Date().getTime();
if (now > item.expires) {
// 如果已过期,则删除该值并返回null
localStorage.removeItem(key);
return null;
}
return item.value;
}
使用示例:
// 设置token,过期时间为1小时(毫秒单位)
setLocalStorageWithExpire('userToken', 'abcdef123456', 1000*60*60);
// 过一段时间侯,尝试获取token
const token = getLocalStorageWithExpire('userToken');
if (token) {
console.log('该用户token为:', token);
} else {
console.log('用户未登陆或登陆已过期');
}
总结
通过这两个简单的函数,我们可以在 localStorage
中实现带过期时间的键值存储,从而更灵活地管理我们的应用数据。