【问题标题】:Deleted items from local storage persist after refresh (vanilla JS)刷新后从本地存储中删除的项目仍然存在(vanilla JS)
【发布时间】:2020-12-12 11:40:48
【问题描述】:

我有一个费用跟踪器,我在其中将费用添加到表中,并将其保存到 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;
}

【问题讨论】:

  • 您能发布您的Store.getLineItems() 实现吗?
  • 当然可以。
  • 嗯,我觉得很好。你有没有用开发工具检查你的代码哪里出错了,本地存储实际包含什么字符串?
  • 我一直在查看控制台和应用程序选项卡。没有错误,所以这让我很困惑。在“应用程序”选项卡中,当我单击删除按钮时,没有从本地存储中删除任何内容。在以前使用本地存储时,当数组中没有更多项目时,存储中只有一个空数组。所以我知道问题是它没有被删除。我只是不明白为什么。
  • Bergi,我刚刚想通了,请参阅下面的帖子。谢谢你的帮助!!当您询问本地存储实际包含什么字符串时,我并没有真正理解您的意思。但这促使我查看存储中的数据并意识到 id 被存储为字符串,而不是数字。

标签: javascript filter local-storage splice


【解决方案1】:

天哪。我刚刚想通了。我设置的 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));

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2018-11-12
    • 2023-03-16
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多