Javascript 为什么在我用componentDidMount中的响应填充状态后,配方没有显示在应用程序中
在我调用setState方法到this.state.components之后,配料数据没有显示在页面上 我尝试更改代码中的不同参数,如res.data.recipes等Javascript 为什么在我用componentDidMount中的响应填充状态后,配方没有显示在应用程序中,javascript,reactjs,components,axios,react-lifecycle,Javascript,Reactjs,Components,Axios,React Lifecycle,在我调用setState方法到this.state.components之后,配料数据没有显示在页面上 我尝试更改代码中的不同参数,如res.data.recipes等 import React from 'react'; import Form from './RecipeForm'; import axios from 'axios'; const API_KEY = 'f562842f0ff6b2d4fd24b9601aeb5e1b'; class HomeScreen extends
import React from 'react';
import Form from './RecipeForm';
import axios from 'axios';
const API_KEY = 'f562842f0ff6b2d4fd24b9601aeb5e1b';
class HomeScreen extends React.Component {
state = {
ingredients: []
};
componentDidMount() {
axios
.get(
'https://www.food2fork.com/api/search?key=f562842f0ff6b2d4fd24b9601aeb5e1b&q=shredded%20chicken'
)
.then(res => {
console.log(res);
this.setState({
ingredients: res.data
});
});
}
render() {
const recipeList = this.state.ingredients.length ? (
this.state.ingredients.map(ingredient => {
return (
<div key={ingredient.recipe_id}>
<p>{ingredient}</p>
</div>
);
})
) : (
<div>There are no ingredients here</div>
);
return (
<div style={{ padding: 50 }}>
<Form />
<div>{recipeList}</div>
</div>
);
}
}
export default HomeScreen;
在
componentDidMount
中,您需要将components
设置为res.data.receipes
,而不是res.data
res.data
只是服务器的响应负载。如果要访问其中的一些数据,则必须进一步索引到响应对象中。然而,这并不总是好的,因为有时(如果发生错误)配方可能不存在。在这种情况下,应该有一个catch
块(如中所示)
可能是因为您达到了API限制,否则,如果看不到响应数据结构,听起来您没有正确地将数据存储到state,这使得this.state.components.length
始终false
,因为obj.length未定义或不正确data
键中有什么?您能编辑您的问题,从您的数据库中添加res.data
console.log
?感谢大家迄今为止的帮助@technogeek1995我在render方法下记录了this.state.components。它在状态中显示信息,但是,没有呈现到界面上。哇,实际上就是这样!非常感谢@技术专家1995
config: {url: "https://www.food2fork.com/api/search?key=bfb76b78b11e7308cc3c027865a508dd&q=shredded%20chicken", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
data:
count: 30
recipes: Array(30)
0: {publisher: "Closet Cooking", f2f_url: "http://food2fork.com/view/35171", title: "Buffalo Chicken Grilled Cheese Sandwich", source_url: "http://www.closetcooking.com/2011/08/buffalo-chicken-grilled-cheese-sandwich.html", recipe_id: "35171", …}
1: {publisher: "All Recipes", f2f_url: "http://food2fork.com/view/29159", title: "Slow Cooker Chicken Tortilla Soup", source_url: "http://allrecipes.com/Recipe/Slow-Cooker-Chicken-Tortilla-Soup/Detail.aspx", recipe_id: "29159", …}
2: {publisher: "My Baking Addiction", f2f_url: "http://food2fork.com/view/e7fdb2", title: "Mac and Cheese with Roasted Chicken, Goat Cheese, and Rosemary", source_url: "http://www.mybakingaddiction.com/mac-and-cheese-roasted-chicken-and-goat-cheese/", recipe_id: "e7fdb2", …}```
this.setState({
ingredients: res.data.receipes
});