javascript - 刷新后从本地存储中删除的项目仍然存在(vanilla JS)
问题描述
我有一个费用跟踪器,我在其中将费用添加到表中,并将其保存到 localStorage 并在 UI 上显示这些项目。但是,当我删除一个项目时,它并没有像应有的那样从 localStorage 中删除。它从 UI 中删除,然后在刷新时返回。
当我试图更好地理解面向对象编程时,我使用了 Brad Traversy 教程 ( https://www.youtube.com/watch?v=JaMCxVWtW58&t=811s ) 来获取结构方面的帮助。我在网上看到其他人的结构完全相同,只是名字不同。但到目前为止,还没有答案。
代码分为 3 个不同的类,LineItem、UI 和用于 localStorage 的 Store。这是我的 Store 类中的 remove 方法:
static removeLineItem(id) {
let lineItems = Store.getLineItems();
lineItems.forEach((lineItem, index) => {
if(lineItem.id === id) {
lineItems.splice(index, 1);
}
});
localStorage.setItem('lineItems', JSON.stringify(lineItems));
}
这就是它的名字:
document.querySelector('.table').addEventListener('click', (e) => {
// Remove lineItem from Store
Store.removeLineItem(e.target.parentElement.previousElementSibling.innerText)
});
这是每一行的标记,用于显示当我遍历 DOM 时 id 的来源:
const lineItemRow = document.createElement("tr");
lineItemRow.classList.add("table-success", "line-item");
lineItemRow.innerHTML = `
<th>${lineItem.name}</th>
<td>$${lineItem.amount}</td>
<td>${lineItem.date}</td>
<td>${lineItem.id}</td>
<td class="btn-container">
<span class="badge badge-pill badge-danger cursor-pointer delete">X</span>
</td>
`
我尝试使用 filter() 而不是 splice() 但它不起作用。
const filteredLineItems = lineItems.filter(lineItem => lineItem.id !== id);
我已经读过 splice() 不是最好的方法,因为它可能会搞砸,但除了过滤器之外,我不知道有任何其他方法可以做到这一点。我之前也曾多次在 React Apps 中使用 filter() 并且效果很好。所以我不明白为什么它至少过滤不起作用。
也没有错误消息。我已经在 remove 方法和 eventListener 中记录了 id,它们都显示得很好。
任何帮助将不胜感激。如果您需要查看另一段代码或标记,请告诉我。
编辑: Store.getLineItems()
static getLineItems() {
let lineItems;
if(localStorage.getItem('lineItems') === null) {
lineItems = [];
} else {
lineItems = JSON.parse(localStorage.getItem('lineItems'));
}
return lineItems;
}
解决方案
天啊。我只是想通了。我设置的 id 是一个数字。(我使用了 Math.random()) 在这个方法中,我使用 === 来比较类型,而不仅仅是值。在本地存储中,id 存储为字符串,而不是数字。所以当然不行。代码只是在做我告诉它做的事情:)
所以我需要使用 == 代替。
static removeLineItem(id) {
let lineItems = Store.getLineItems();
lineItems.forEach((lineItem, index) => {
if(lineItem.id === id) {
lineItems.splice(index, 1);
}
});
localStorage.setItem('lineItems', JSON.stringify(lineItems));
}
推荐阅读
- android - 联系 API 时出错,com.google.android.gms.tasks.RuntimeExecutionException:com.google.android.gms.api.ApiException: 13: 错误
- c++ - 尽管注释掉了所需的头文件,为什么这个 C++ 程序仍能编译和运行?
- angular - Angular 6 子组件不会在 LayoutComponent 中打开
- visual-studio-2017 - Visual Studio 2017 ClickOnce 证书签名已禁用
- c# - 获取所有 Google 电子表格
- ruby-on-rails - 如何为可以是主机、客户或两者兼有的用户建模?导轨
- c# - Unity3D 脚本运行时版本更改给出了奇怪的错误
- amazon-web-services - what is the difference between a load balancer, listener target, target group in AWS?
- css - 在 Angular 材质表中使用省略号
- php - 我无法在同一张表中正确打印来自 2 个 rest api 的值