当应用程序通过实时服务器 运行 时,localStorage 是否应该保留?

Should localStorage persist when application is run via live server?

我正在 运行通过 VSCode 的 Live Server 扩展申请。

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

但是,每当我刷新页面或导航到同一应用程序中的不同页面时,我的 localStorage 就会被清除。

在将项目写入 localStorage 时,我尝试调用 localStorage 简写以及更明确的 window.localStorage。两者都没有解决这个问题。

当应用程序在本地或通过实时服务器 运行 时,localStorage 不会持续存在吗?我怀疑应该这样做,但我做错了其他事情。

MDN documentation提到:

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed. (Data in a localStorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.)

难道实时服务器上的每次刷新或页面更改都代表一个全新的设备历史记录? (再说一次,这似乎有道理,但仍然不太可能。不过,我很高兴自己错了。)

提前感谢您提供的任何指导。


编辑 - 这是一些相关代码:

在全局范围内:

const cartItems = [];
localStorage.setItem('cartItemsKey', JSON.stringify(cartItems));
localStorage.getItem('cartItemsKey');
const cartItemsInStorage = localStorage.getItem('cartItemsKey');

封装 - 单击添加到购物车按钮时将触发此函数。为简洁起见,省略了大部分内容,除了与 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));
}

所以每次页面重新加载时,我实际上是 re-writing 一个空数组到 localStorage。

我通过删除 .setItem 行解决了这个问题,如下所示:

const cartItems = [];
localStorage.getItem('cartItemsKey');
const cartItemsInStorage = localStorage.getItem('cartItemsKey');

现在,我将我的初始 const cartItems = []; 重写为条件语句,我首先检查 cartItemsKey 是否存在于全局存储中。如果是这样,我将设置cartItems = JSON.parse(localStorage.getItem('cartItemsKey')。否则我会设置cartItems = [];.

非常感谢@Alex Rasidakis 的帮助。