javascript - 首次获取后将数据存储到本地存储中
问题描述
我能够从 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()]));
}
解决方案
LocalStorage 将数据保存为字符串键/值对格式,因此在保存数据之前保存将对象转换为字符串使用
JSON.stringify(json.data.patient)
保存时
localStorage.setItem('patients',JSON.stringify(json.data.patient))
检索时
let patients = JSON.parse(localStorage.getItem('patients'));
推荐阅读
- amazon-web-services - 连接到 Amazon RDS (Microsoft SQL Server / PostrgreSQL) 时超时
- python - 通过电子邮件将 DF 作为附件发送
- python - 如何使用 python 定期从弹性数据库中获取数据?
- android - Android ConstraintLayout - 如何将视图移动到占用空间?
- chapel - 教堂领域:`low/high` 和 `first/last` 方法之间的区别
- java - 使用 useDelimiter() 连接子字符串
- docker - dashDB 容器部署期间的致命运行时错误
- python - 如果dict没有键或值为空,python返回None
- vb.net - Renci.SSHnet.Sftp 超时错误
- xcode - AndroidDeveloper 可以像 XCode 的 // MARK: - ... 做任何事情吗?