如何强制刷新整个本地存储?

huangapple go评论67阅读模式
英文:

How can I force refresh of the entire local storage?

问题

我正在创建一个购物车。
基本上,当我重新加载带有购物车中的产品的页面时,本地存储不会刷新,这正是我想要的。

但我也希望它在某个时候刷新(当我打开另一个页面时)。如何让本地存储完全刷新?

英文:

I am creating a shopping cart.
Basically, when I reload the page with the products in my cart, the local storage doesn't refresh, which is what I want.

But I also want it to refresh at some point only (when I open another page). How do I get the local storage to refresh completly?

答案1

得分: 1

localStorage.clear()

Storage 接口的 clear() 方法会清除给定 Storage 对象中存储的所有键。

例如:

// 存储数据到本地存储
localStorage.setItem('foo', 'bar');
localStorage.setItem('john', 'wick');
localStorage.setItem('joe', 'doe');

// 从本地存储中获取键 'foo' 的值
console.log(localStorage.getItem('foo')) // 输出 'bar'

// 清除所有数据
localStorage.clear();

// 现在如果尝试再次获取 'foo' 键的值,将输出 null
console.log(localStorage.getItem('foo')) // 输出 null
英文:

localStorage.clear()

The clear() method of the Storage interface clears all keys stored in a given Storage object.

for example

//feeds storage
localStorage.setItem('foo', 'bar');
localStorage.setItem('john', 'wick');
localStorage.setItem('joe', 'doe');

//lets get the value bar from the localStorage
console.log(localStorage.getItem('foo'))//outputs 'bar'

//clears all data
localStorage.clear();

//now if you try to do it again after you clear it will print null
console.log(localStorage.getItem('foo'))//outputs null

答案2

得分: 0

你可以在用户关闭标签页时使用会话存储来删除数据,localStorage 不会在页面刷新或其他操作时刷新,你需要使用相同的键来使用 setItem,并传递新的或更新的数据(你想要更改的数据):

localStorage.setItem("你之前使用过的相同对象键", 数据);

通过这样做,数据(更新后的数据)将被存储在localStorage中。

英文:

You can use session storage if you want to delete data anytime user closes the tab, localStorage does not refresh on page refresh or anything like that, what you have to do is use setItem on same key you were using before and pass new or updated data(data you want to change)

localStorage.setItem("same-object-key-you-have-used-before",data);

by doing this data(updated one) will be stored in localStorage

huangapple
  • 本文由 发表于 2023年2月9日 01:04:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定