【问题标题】:Save JSON in Local Storage after the fetch提取后将 JSON 保存在本地存储中
【发布时间】:2021-09-10 12:58:30
【问题描述】:

对不起,如果这个帖子很多,我阅读了几篇文章但找不到解决方案。所以,我从这个 API 获取一个大的JSON,我想以某种方式在localStorage 中缓存响应,所以下次页面加载时,脚本首先检查是否有请求的对象JSON 中的 ID,如果有则渲染内容 - 如果没有,则转到 API 来获取它。

我正在考虑设置两个 fetch() 函数,这就是我所拥有的:

   fetch(url + id)
        .then((response) => {
            localStorage.setItem('myResponse', response);
        })              
        .catch((error) => {
            console.log(error);
        })

然后,检查localStorage中是否保存了一些东西,如果它是好的,用它来渲染HTML,如果没有,继续另一个fetch,从API中获取它。

  if(localStorage) {
     createHTML(localStorage.myResponse);
  } else {
     fetch(url + id)
         .then(response => response.json())
         .then(data => createHTML(data))
  }    

但是,在第一次提取中,如果我使用 JSON.stringify(response),它只会将其显示为一个空对象,因此它是 localStorage,它看起来像:myResponse - {}。如果我在第一次提取时执行console.log(response.json());,它会显示Promise {<pending>}

我试图从中做出一些事情,但没有结果......非常感谢任何帮助!

【问题讨论】:

    标签: javascript json caching fetch local-storage


    【解决方案1】:

    response.json() 是一个 Promise,它需要是 awaited,或者链接到 .then();如果您只是按原样记录它,您将得到的只是Promise {<pending>},因为它还没有解决。

    fetch(url + id)
            .then( response => response.json() )
            .then( json => {
                localStorage.setItem('myResponse', JSON.stringify(json));
            })
    

    或者使用 async/await 语法:

    const response = await fetch(url + id);
    const json = await response.json();
    localStorage.setItem('myResponse', JSON.stringify(json));
    

    【讨论】:

    • 谢谢,好的,现在我的 localStorage 看起来像这样:myResponse - [object Object]。以后如何在我的 if 语句中使用它..?
    • 啊,你只需要把它串起来,更新我的答案。如果你不这样做,你实际上是在存储字符串"[object Object]",所以它没用
    • 啊...所以我需要第一个 .then 将响应转换为带有 response.json() 的 JS 对象,(API url 在我的浏览器中显示 JSON,不知道为什么我需要准确地运行该方法 - 我猜它对 JS 来说是可读的?)。无论如何,当该数据转换为 JS 对象时,我还需要一个 .then(json => localStor...) 来“字符串化”它 - 所以它又转换为类似 JSON 的格式,可以保存进入本地存储?我做对了吗?非常感谢,这花了我几个小时才让它工作!
    • 我建议放弃.then() 语法,因为处理它绝对是一件痛苦的事情,一直使用async/await,它基本上是异步代码编写的同步代码。它更易于阅读、处理和调试。
    猜你喜欢
    • 2016-04-29
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2015-10-23
    • 2013-02-02
    相关资源
    最近更新 更多