当应用程序通过实时服务器运行时,本地存储是否应该持久化?

3

我正在使用VSCode的Live Server扩展程序运行一个应用程序。

这个应用程序(电子商务网站)将物品保存到cartItems数组中,每当单击addToCart按钮时,该数组就会被写入localStorage。当执行指定操作时,我可以在DevTools / Application / LocalStorage中看到项目被正确保存。

然而,每当刷新页面或在同一应用程序内导航到其他页面时,我的localStorage都会被清除。

当将项目写入localStorage时,我尝试调用localStorage简短命令,以及更明确的window.localStorage,但对于此问题,两种方法都没有起作用。

当本地运行或通过实时服务器运行应用程序时,localStorage是否不会持久保留?我怀疑它应该可以,并且我正在做一些其他不正确的事情。

MDN文档提到:

只读的localStorage属性允许您访问Document的来源的Storage对象;存储的数据会跨浏览器会话保存下来。 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));
}

我可以看到,根据下面的屏幕录像,项目已经成功保存到本地存储中。问题出现在我刷新或更改页面时。

local-storage-issue

2个回答

2

更新:

我找到了问题所在。

我在全局范围内有以下代码:

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 的帮助。

1

您能提供给我们一些代码吗?我认为Live Server与您所说的本地存储故障无关。

我很确定这是一个浏览器问题。也许您每次刷新时都在使用硬刷新。也许您有一些设置清除本地存储或某些浏览器扩展程序每次刷新时都会清理您的页面。

尝试从其他浏览器(如Mozilla、Edge等)打开您的localhost地址,并告诉我们它的行为。


是的,我会编辑我的初始问题并添加一些代码。关于浏览器,我默认使用Brave。然而,我刚刚尝试在Chrome和Firefox上运行应用程序(通过实时服务器)- 我仍然遇到了同样的问题。我没有任何浏览器扩展。 - mikekoscinski
1
你确定没有任何JavaScript代码在幕后执行这项工作吗?尝试在项目中搜索storage.clear();或localStorage.clear();。如果找到它们并且你不想要它们存在,请将其删除。 - Alex Rasidakis
刚刚完成了我上面的编辑。在我的addToCart()函数中,我有两行代码,在那里我删除了该项,然后重新设置了它。然而,即使我删除.removeItem()调用,问题仍然存在。 - mikekoscinski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接