英文:
Error while rendering an array.map() in React
问题
我对React非常新,这可能是一个愚蠢的问题,但我收到了一个错误消息:在尝试显示每个食谱的成分时出现错误,错误消息是:“Uncaught TypeError: 无法读取未定义属性 'map'。我不确定是否可以在返回语句内部使用数组.map,或者如果它是我的组件的一部分,我应该在哪里包含它?我只是想浏览成分并显示它们。感谢任何帮助!
import React, { Component } from "react";
class Recipe extends Component {
state = {
activeRecipe: []
}
componentDidMount = async() => {
const title = this.props.location.state.recipe;
const req = await fetch
(`https://api.edamam.com/search?q=${title}&app_id=${API_ID}&app_key=${API_KEY}`);
const res = await req.json();
this.setState({ activeRecipe: res.hits[0].recipe});
console.log(this.state.activeRecipe);
}
render() {
const recipe = this.state.activeRecipe;
return (
<div className="container">
<div className="active-recipe">
<h3 className="active-recipe">{recipe.label}</h3>
<div className="container">
{recipe.ingredients && recipe.ingredients.map(ingredient => {
return (
<p>{ingredient.text}</p>
);
})}
</div>
</div>
</div>
);
}
}
export default Recipe;
<details>
<summary>英文:</summary>
I'm super new to React and this might be a dumb question but I'm getting an error saying: `Uncaught TypeError: Cannot read property 'map' of undefined
` when I'm trying to display the ingredients for each recipe. I'm not sure if I can use an array.map inside of the return statement, or where else should I include it, if it is a part of my component? I just want to go through the ingredients and display them . Thanks for any help![![Screenshot of my console][1]][1]
import React, { Component } from "react";
class Recipe extends Component {
state = {
activeRecipe: []
}
componentDidMount = async() => {
const title = this.props.location.state.recipe;
const req = await fetch
(`https://api.edamam.com/search?q=${title}&app_id=${API_ID}&app_key=${API_KEY}`);
const res = await req.json();
this.setState({ activeRecipe: res.hits[0].recipe});
console.log(this.state.activeRecipe);
}
render() {
const recipe = this.state.activeRecipe;
return (
<div className="container">
<div className="active-recipe">
<h3 className="active-recipe">{recipe.label}</h3>
<div className="container">
{recipe.ingredients.map(ingredient => {
return (
<p>{ingredient.text}</p>
);
})}
</div>
</div>
</div>
);
}
}
export default Recipe;
[1]: https://i.stack.imgur.com/0SFSZ.png
</details>
# 答案1
**得分**: 1
这是因为您的组件在异步调用完成之前已呈现/挂载。如果您将以下代码更改为:
```jsx
recipe.ingredients && recipe.ingredients.map(ingredient => {
它应该按您想要的方式工作。这是因为只有在存在ingredients时才会调用map方法。
英文:
This is because your component is rendered/mounted before the async call can finish..
If you change:
recipe.ingredients.map(ingredient => {
to this:
recipe.ingredients && recipe.ingredients.map(ingredient => {
It should work as you are wanting.
This is because map does not get called unless ingredients exist.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论