javascript - ReactJS:从 JSON 文件中提取数据时出错
问题描述
我正在尝试将数据从我的 JSON 文件传递到我的 ReactJS 应用程序,但收到以下错误:
TypeError:无法读取
'mainPage'
未定义的属性
如果我尝试siteData
仅使用 console.log,它将运行良好。我猜这个问题可能与访问对象参数有关
你能告诉我我做错了什么吗?
这是我的 JSON 对象:
{
"data": {
"mainPage": {
"navBar": ["HR", "HR1", "HR2"],
"name": "Name one",
"agency": "agency one"
},
"secondPage": {
"rank": 2,
"name": "Name Two",
"agency": "agency two"
},
"thirdPage": {
"rank": 3,
"name": "Name Three",
"agency": "agency three"
}
}
}
我的 .jsx 文件:
import React from 'react';
import axios from 'axios';
import logo from '../img/company_logo.png';
import '../css/header.scss';
export default class Header extends React.Component {
constructor() {
super();
this.state = {
siteData: {},
};
}
componentDidMount() {
axios.get('./data.json')
.then((res) => {
this.setState({
siteData: res.data,
});
})
.catch((err) => {
console.log(err);
});
}
render() {
// console.log(this.state);
const { siteData } = this.state;
console.log(siteData.data.mainPage);
return (
<div className="headerWrapper">
<a href=".../public/index.html">
<img src={logo} alt="company_logo" id="companyLogo" />
</a>
<ul>
<li>Navbar_1</li>
<li>Navbar_2</li>
<li>Navbar_3</li>
</ul>
</div>
);
}
}
解决方案
发生这种情况是因为在组件的初始渲染之后componentDidMount
运行。您可以在此处检查组件的生命周期,其中声明:
componentDidMount() 方法在组件输出被渲染到 DOM 之后运行。
在 render 方法中,您应该检查这是否为 null,与异步 (AJAX) Web 调用一样,无法保证您可以在初始渲染发生之前检索数据,即使您在渲染发生之前调用 AJAX。
推荐阅读
- qt - 如何在不手动操作 .ui 文件的情况下在 QtDesigner 中编辑 QtElement 的网格位置?
- python - DJANGO gte, lte 没有显示任何结果
- wpf - 从 WPF-Windows (XAML) 调用 WPF-Control 中的 RelayCommand
- serialization - 如何在 Hazelcast 上安排在 IMap 上查询的任务?
- r - 如何在 R 中创建一个用户生成的函数,将列中的所有值转换为日期格式?
- firebase - Flutter/Firebase 错误 - 未处理的异常:类型 '_CompactLinkedHashSet
' 不是类型 'FutureOr 的子类型 >>' - java - AltUnityDriver create-无法执行命令'mobiledevice tunnel -u (device udid)13000 13000'
- blazor - Blazor - 在 RenderFragment 部分刷新子组件
- shell - 如何将变量从一个目录存储或捕获到另一个目录并在 Linux 中使用 cut 命令执行
- reactjs - 在 Windows 上运行多个反应应用程序时无法识别端口