【发布时间】:2019-10-02 10:54:50
【问题描述】:
我正在尝试将数据从我的 JSON 文件传递到我的 ReactJS 应用程序,但收到以下错误:
TypeError: 无法读取未定义的属性
'mainPage'
如果我只尝试 console.log siteData,它将运行良好。我猜这个问题可能与访问对象参数有关
你能告诉我我做错了什么吗?
这是我的 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>
);
}
}
【问题讨论】:
-
siteData.data未定义。您可能缺少嵌套级别。试试siteData.mainPage? -
看起来 siteData.data 未定义,请检查您是否使用控制台或警报获取数据
-
如果我 console.log
siteData.data它会显示我的对象 -
必须是
siteData.mainPage
标签: javascript json reactjs