【问题标题】:LocalStorage.getLocalStorage is not a function - JS DOM ManipulationLocalStorage.getLocalStorage 不是函数 - JS DOM 操作
【发布时间】:2022-12-07 15:13:57
【问题描述】:

我正在创建一个程序,我将数据存储在本地存储中。每当我单击添加/删除按钮时,我都会收到此错误。 LocalStorage.get LocalStorage 不是函数

下面是我的本地存储类

class LocalStorage {
  constructor(storageKey) {
    this.storageKey = storageKey;
  }

 getLocalStorage = () => JSON.parse(localStorage.getItem(this.storageKey));

 setLocalStorage = (data) => localStorage.setItem(this.storageKey, JSON.stringify(data));
}

export default LocalStorage;

我在下面的这个代码块中导入这个类

class SaveAll {
  
save = (title, author) => {
    let books = [];
    if (localStorage.getItem('book') === null) {
      books = [];
    } else {
      // books = JSON.parse(localStorage.getItem('book'));
      books = LocalStorage.getLocalStorage('books');
    }
    const book = { text1: title, text2: author };
    books.push(book);
    // localStorage.setItem('book', JSON.stringify(books));
    LocalStorage.setLocalStorage(books);
  }

}

这是 UI 的提取代码

static renderBooks = () => {
    bookText.innerHTML = '';
    let books = [];
    if (localStorage.getItem('book') === null) {
      books = [];
    } else {
      books = JSON.parse(localStorage.getItem('book'));

      books.forEach((book) => {
        bookText.innerHTML += `
            <div class="wrapper">
              <p class="book-title">${book.text1}</p>
              <p class="book-author">${book.text2}</p>
              <button onclick="deleteBook('${book.text1}', 
              '${book.text2}')">Remove</button>
            </div>
            `;
      });
    }
  }

我已经尝试在 home.html 文件中实现代码,但它没有用,所以我选择将它们提取到一个单独的 js 文件中,但仍然没有用

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您正在尝试访问没有类实例的类方法,所以我建议将您的方法设为静态

    class LocalStorage {
      constructor(storageKey) {
        this.storageKey = storageKey;
      }
    
     static getLocalStorage = () => JSON.parse(localStorage.getItem(this.storageKey));
    
     static setLocalStorage = (data) => localStorage.setItem(this.storageKey, JSON.stringify(data));
    }
    

    这将解决您的问题,因为无需类实例即可访问静态方法

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 2013-08-12
      相关资源
      最近更新 更多