简体   繁体   English

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

[英]Should localStorage persist when application is run via live server?

I am running an application via VSCode's Live Server extension.我正在通过 VSCode 的Live Server扩展运行一个应用程序。

This application (e-commerce website) saves items to a cartItems array that gets written to localStorage whenever an addToCart button is clicked.此应用程序(电子商务网站)将项目保存到一个 cartItems 数组,只要单击 addToCart 按钮,该数组就会写入 localStorage。 I can see in DevTools/Application/LocalStorage that the items are being saved correctly when the specified actions are taken.我可以在 DevTools/Application/LocalStorage 中看到,当执行指定的操作时,项目正在正确保存。

However, my localStorage is cleared whenever I refresh the page or navigate to a different page within the same application.但是,每当我刷新页面或导航到同一应用程序中的不同页面时,都会清除我的 localStorage。

When writing items to localStorage, I have tried invoking the localStorage short-hand, as well as the more explicit window.localStorage .将项目写入 localStorage 时,我尝试调用localStorage简写,以及更明确的window.localStorage Neither has worked for this issue.两者都没有解决这个问题。

Does localStorage not persist when an application is run locally or via a live server?当应用程序在本地或通过实时服务器运行时,localStorage 是否不会持续存在? I suspect it should and I am doing something else incorrectly.我怀疑它应该并且我做的其他事情不正确。

The MDN documentation mentions: MDN 文档提到:

The read-only localStorage property allows you to access a Storage object for the Document 's origin;只读localStorage属性允许您访问Document来源的Storage对象; 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. localStoragesessionStorage类似,不同之处在于虽然localStorage中存储的数据没有过期时间,但sessionStorage存储的数据会在页面会话结束时(即页面关闭时)被清除。 (Data in a localStorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.) (当最后一个“私人”选项卡关闭时,在“私人浏览”或“隐身”会话中创建的localStorage对象中的数据将被清除。)

Could it be that each refresh or page change on live server represents an entirely new device history?会不会是实时服务器上的每次刷新或页面更改都代表了一个全新的设备历史记录? (Again, this feels plausible but still unlikely. I am happy to be wrong, however.) (同样,这感觉似乎有道理,但仍然不太可能。不过,我很高兴自己错了。)

Thank you in advance for any guidance you can provide.预先感谢您提供的任何指导。


EDIT - Here is some of the relevant code:编辑 - 这是一些相关的代码:

In the global scope:在全球范围内:

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

Encapsulated - this function fires when an addToCart button is clicked.封装 - 单击 addToCart 按钮时会触发此函数。 Omitting most of it, except the part pertaining to localStorage , for brevity:省略大部分,除了与localStorage相关的部分,为简洁起见:

function addToCart (button) {
    // Create newCartItem object using relevant data
    cartItems.push(newCartItem);
        localStorage.removeItem('cartItemsKey');
        localStorage.setItem('cartItemsKey', JSON.stringify(cartItems));
}

Again, I can see that the items are successfully being saved to localStorage, per the below screen recording.再一次,根据下面的屏幕录制,我可以看到这些项目已成功保存到 localStorage。 It's when I refresh or change pages that I have trouble.当我刷新或更改页面时,我遇到了麻烦。

本地存储问题

Can you provide us with some code?你能给我们提供一些代码吗? I don't think that the Live Server has anything to do with the local storage malfunction you are talking about.我认为 Live Server 与您所说的本地存储故障没有任何关系。

I'm pretty sure it's a browser issue.我很确定这是浏览器的问题。 Maybe you are using hard refresh somehow each time you are refreshing.也许您每次刷新时都以某种方式使用硬刷新。 Maybe you have some setting that clears the local storage or some browser extension that cleans your page every time you refresh.也许您有一些设置可以清除本地存储或某些浏览器扩展程序可以在每次刷新时清除您的页面。

Try to open your localhost address from another browser like Mozilla, Edge etc. and tell us about its behaviour.尝试从 Mozilla、Edge 等其他浏览器打开您的本地主机地址,并告诉我们它的行为。

Update:更新:

I figured out what the issue was.我想通了是什么问题。

I have the following code in the global scope:我在全局范围内有以下代码:

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

Which gets called before this code:在此代码之前调用它:

function addToCart (button) {
    // Create newCartItem object using relevant data
    cartItems.push(newCartItem);
        localStorage.removeItem('cartItemsKey');
        localStorage.setItem('cartItemsKey', JSON.stringify(cartItems));
}

So I was effectively re-writing an empty array into localStorage every time the page reloaded.因此,每次页面重新加载时,我都会有效地将一个空数组重新写入 localStorage。

I have resolved this issue by removing the .setItem line as follows:我通过删除.setItem行解决了这个问题,如下所示:

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

Now, I will rewrite my initial const cartItems = [];现在,我将重写我的初始const cartItems = []; as a conditional statement, where I first check to see if cartItemsKey exists in global storage.作为条件语句,我首先检查全局存储中是否存在 carItemsKey。 If so, I will set cartItems = JSON.parse(localStorage.getItem('cartItemsKey') . Otherwise, I will set cartItems = []; .如果是这样,我将设置cartItems = JSON.parse(localStorage.getItem('cartItemsKey') 。否则,我将设置cartItems = [];

Thank you very much, @Alex Rasidakis, for your kind help.非常感谢@Alex Rasidakis,感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM