问题描述
我正在通过VSCode的Live Server扩展名运行应用程序。
此应用程序(电子商务网站)将项目保存到cartItems数组,每当单击addToCart按钮时,该数组就会写入到localStorage中。我可以在DevTools / Application / LocalStorage中看到,当执行指定的操作时,这些项已正确保存。
但是,每当我刷新页面或导航到同一应用程序中的另一个页面时,都会清除localStorage。
在将项目写入localStorage时,我曾尝试调用localStorage
的简写形式以及更明确的window.localStorage
。都没有解决这个问题。
在本地运行或通过实时服务器运行应用程序时,localStorage是否不持久?我怀疑应该这样做,而且我做错了其他事情。
只读的
localStorage
属性使您可以访问Storage
Document
来源的对象;存储的数据保存在 浏览器会话。localStorage
与sessionStorage
类似,除了 虽然存储在localStorage
中的数据没有到期时间,但是数据 页面会话结束时,存储在sessionStorage
中的存储将被清除- 也就是关闭页面时。 (localStorage
对象中的数据 在“私人浏览”或“隐身”会话中创建的内容在 最后一个“私人”标签已关闭。)
是不是实时服务器上的每次刷新或页面更改都代表了全新的设备历史记录? (再次,这听起来似乎合理,但仍然不太可能。不过,我很高兴错了。)
在此先感谢您提供的任何指导。
编辑-以下是一些相关代码:
在全局范围内:
const cartItems = [];
localStorage.setItem('cartItemsKey',JSON.stringify(cartItems));
localStorage.getItem('cartItemsKey');
const cartItemsInStorage = localStorage.getItem('cartItemsKey');
已封装-单击addToCart按钮时将触发此函数。为简洁起见,除与localStorage
有关的部分外,省略了大部分内容:
function addToCart (button) {
// Create newCartItem object using relevant data
cartItems.push(newCartItem);
localStorage.removeItem('cartItemsKey');
localStorage.setItem('cartItemsKey',JSON.stringify(cartItems));
}
同样,根据下面的屏幕记录,我可以看到项目已成功保存到localStorage。当我刷新或更改遇到问题的页面时。
解决方法
您能提供一些代码吗?我认为Live Server没有任何功能 与您正在谈论的本地存储故障有关。
我很确定这是浏览器问题。也许您正在以某种方式使用硬刷新 每次您刷新时。也许您有一些设置可以清除本地存储,或者有些浏览器扩展可以在每次刷新时清除您的页面。
尝试从另一个浏览器(例如Mozilla,Edge等)打开您的本地主机地址。 并告诉我们它的行为。
,更新:
我弄清楚了问题所在。
我在全局范围内有以下代码:
const cartItems = [];
localStorage.setItem('cartItemsKey',JSON.stringify(cartItems));
localStorage.getItem('cartItemsKey');
const cartItemsInStorage = localStorage.getItem('cartItemsKey');
在此代码之前会被调用:
function addToCart (button) {
// Create newCartItem object using relevant data
cartItems.push(newCartItem);
localStorage.removeItem('cartItemsKey');
localStorage.setItem('cartItemsKey',JSON.stringify(cartItems));
}
因此,每次页面重新加载时,我都会有效地将一个空数组重新写入localStorage。
我已通过删除.setItem
行来解决此问题,如下所示:
const cartItems = [];
localStorage.getItem('cartItemsKey');
const cartItemsInStorage = localStorage.getItem('cartItemsKey');
现在,我将把初始的const cartItems = [];
重写为条件语句,在此首先检查全局存储中是否存在cartItemsKey。如果是这样,我将设置cartItems = JSON.parse(localStorage.getItem('cartItemsKey')
。否则,我将设置cartItems = [];
。
非常感谢@Alex Rasidakis,谢谢您的帮助。