我正在从用于食品食谱的外部API获取数据,并以这种格式(JSON)获取响应:
{
"count": 30,
"recipes": [
{
"publisher": "BBC Food",
"f2f_url": "http://food2fork.com/view/8c0314",
"title": "Chicken and cashew nut stir-fry",
"source_url": "http://www.bbc.co.uk/food/recipes/chickenandcashewnuts_89299",
"recipe_id": "8c0314",
"image_url": "http://static.food2fork.com/chickenandcashewnuts_89299_16x9986b.jpg",
"social_rank": 95.91061636245128,
"publisher_url": "http://www.bbc.co.uk/food"
},
{
"publisher": "Jamie Oliver",
"f2f_url": "http://food2fork.com/view/0beb06",
"title": "Roasted chicken breast with pancetta, leeks & thyme",
"source_url": "http://www.jamieoliver.com/recipes/chicken-recipes/roasted-chicken-breast-with-pancetta-leeks-and-thyme",
"recipe_id": "0beb06",
"image_url": "http://static.food2fork.com/466_1_1349094314_lrg2129.jpg",
"social_rank": 94.88568903341375,
"publisher_url": "http://www.jamieoliver.com"
},
{ ... more recipes ... }
]
}
为了进行测试,我试图访问该数据并显示,只是变量“ count”和数组中第一个配方的“发布者”。这是我的React代码:
import React from 'react';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { data: {} };
}
componentDidMount() {
fetch('https://www.food2fork.com/api/search?key=MY_KEY&q=chicken%20breast&page=2')
.then(response => {
return response.json();
})
.then(jsonData => {
this.setState({ data: jsonData }, function() {
console.log(jsonData);
});
});
}
render() {
return (
<div className="App">
<h1>{this.state.data.count}</h1>
<p>{this.state.data.recipes[0].publisher}</p> // Why this doesn't work?
</div>
);
}
};
如果我在render()函数中删除了'p'标签,那么一切都会按预期进行:首先加载页面,然后在获取数据后,将'30'显示为'h1'。
但是,如果我使用'p'标签运行代码,则会出现此错误:
我正在寻找答案两个多小时,确实找不到答案。为什么我可以访问数组内部的变量“ count”,但不能访问变量“ publisher”?设置它后,我将退出this.state事件,那里的对象看起来完全正常。如何访问“配方”数组中的元素?
答案 0 :(得分:2)
这是因为当时您在获取数据时,react将渲染该组件,并且由于 this.state.data仍为{} 而出现错误,因此 this.state.data。尚未定义配方[0] ,因为获取请求尚未完成(需要一些时间)。要解决此问题,您必须返回2个条件。
2)提取完成后
render() {
if(!this.state.data.recipes){
// if the fetch request is still not completed
return (
<div>
<h1>Loading .... </h1>
</div>
)
}
// run when fetch request is completed and this.state.data is now assigned some data
return (
<div className="App">
<h1>{this.state.data.count}</h1>
<p>{this.state.data.recipes[0].publisher}</p> // Why this doesn't work?
</div>
);
}
this.state.data.count
时,您不会得到任何错误。因为它将打印计数值的 undefined (在那时,如果您这样做,您将不尝试像this.state.data.count.toString()
那样进一步打印,则会通过错误无法读取属性toString()的值未定义)。