javascript - 为什么在 reactjs 中使用 JSON.parse 会导致跨源错误?
问题描述
所以我有一个 JSON 数据数组保存到本地存储,就像这样
localStorage.setItem('user_data', JSON.stringify(data));
像这样从本地存储中获取,但是 console.log(this.state.healthData) 返回 null
constructor(props) {
super(props);
this.state = {
healthData: {}
}
}
this.setState({ healthData: JSON.parse(localStorage.getItem('user_data')) });
但我知道数据可能会被提取,因为 a console.log(localStorage.getItem('user_data'));
打印出这个 {"age":"20","gender":"male","goal":"recomp","height":"181","weight":" 80"}。
所以我也尝试过console.log(JSON.parse(this.state.healthData))
,但这会导致“跨源错误”
问题是此代码适用于我的 app.js 页面,正如您可能在屏幕截图日志中看到的那样
{age: "20", gender: "male", goal: "recomp", height: "181", weight: "80"}.
那么是什么原因造成的,还有其他方法吗?
解决方案
我试着这样做,它完美无缺。
您必须确保状态已更改。(通过回调/useEffect)
test = () => {
const data = {
age: "20",
gender: "male",
goal: "recomp",
height: "181",
weight: "80"
};
localStorage.setItem("user_data", JSON.stringify(data));
this.setState(
{
healthData: JSON.parse(localStorage.getItem("user_data"))
},
() => {
console.log(this.state.healthData);
}
);
};
推荐阅读
- gcc - ARM 的 GCC 是否可以将此标记为警告:A != B;
- java - concat Jolt 转换在演示站点上工作;在代码中不起作用
- docker - 如何将在 Docker 容器中运行的 Grafana 连接到在主机上运行的 Prometheus 数据源(在 Docker for Mac 上)?
- c++ - 接受整数输入并返回字符串的函数
- node.js - 关于如何编写一个简单的 JHipster 模块的教程
- android - 广播接收器没有收到消息
- vb.net - 发送 SMS 的应用程序的问题
- ecmascript-6 - 为什么 ES6 模块可以摇树
- python - 如何使用 BigQuery 和 Apache Beam 将 SQL 表转换为行序列列表?
- javascript - 如何在组件 vuejs 中显示 firebase 子集合