[英]React doesn't render API data
我正在构建一个食谱应用程序,我陷入了困境,没有错误显示或任何可以帮助我的东西,这是我第一次在React和Im中使用APIS,这就是我问的原因。
我正在尝试从此API提取数据, 但我不知道为什么属性不会显示在屏幕上,因为我还有另一个示例。
我可以在带有React Developer扩展的控制台中看到将属性传递给状态,这样很好,而且我不明白为什么我不能访问或为什么它不能呈现。
在另一个示例中,它不是从API获取数据,而是从json中的本地对象获取数据。 使用API时,它的工作原理是否有所不同? 任何想法?
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
recipes: []
};
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch("https://www.themealdb.com/api/json/v1/1/random.php")
.then(response => response.json())
.then(json => {
this.setState({ recipes: json });
})
.catch(error => console.log("parsed error", error));
}
render() {
return <div className="box">{this.state.recipes.strMeal}</div>;
}
}
export default App;
您的代码看起来还不错,但是您需要以某种方式呈现后端数据:
fetchData() {
fetch("https://www.themealdb.com/api/json/v1/1/random.php")
.then(response => response.json())
.then(json => {
this.setState({ recipes: json.meals });
})
.catch(error => console.log("parsed error", error));
}
render() {
return (
<div className="box">
{this.state.recipes.map(m => <p>{m.strMeal}</p>)}
</div>
);
}
recipes
是带有meals
键的json,是数组。 数组中的每个元素都有strMeal
键(餐名)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.