首页 > 解决方案 > 首次获取后将数据存储到本地存储中

问题描述

我能够从 api 获取数据。但是每当页面加载时,我的页面都会不断从 api 获取数据。我尝试使用 localStorage 解决这个问题,如下所示。

我尝试加载存储在 localStorage 中的数据,但只要加载数据,数据就会显示为 [object Object]。如何从响应中获取元素(患者姓名、患者电话)而不是显示 [object Object]。

PS:React 初学者

零件

   componentDidMount()
{
    let patients = localStorage.getItem('patients');
     if(patients)
    {
            this.setState({
            patientData: patients
     })         
    console.log(JSON.stringify(patients));
    }
    else
    {
        this.getPatients();
     }
}

    getPatients(){
    return this.fetchPost().then(([response,json]) => {
       console.log(response);
       if(response.status === 200)
       {             
             this.setState({
             patientDetails: json.data.patient
          })
          localStorage.setItem('patients',json.data.patient)     
       }
    })
 }

     fetchPost(){
        const URL = 'http://domain:3000/api/';
        return fetch(URL, {method:'GET',headers:new Headers ({
           'Accept': 'application/json',
           'Content-Type': 'application/json',
         .then(response => Promise.all([response, response.json()]));
     }

标签: javascriptreactjs

解决方案


LocalStorage 将数据保存为字符串键/值对格式,因此在保存数据之前保存将对象转换为字符串使用

JSON.stringify(json.data.patient)

保存时

localStorage.setItem('patients',JSON.stringify(json.data.patient))  

检索时

let patients = JSON.parse(localStorage.getItem('patients'));

在 localStorage 中存储对象


推荐阅读