[英]Error while rendering an array.map() in React
我是 React 的超級新手,這可能是一個愚蠢的問題,但我收到一條錯誤消息: Uncaught TypeError: Cannot read property 'map' of undefined
的類型錯誤:當我嘗試顯示每個食譜的成分時, Uncaught TypeError: Cannot read property 'map' of undefined
。 我不確定是否可以在 return 語句中使用 array.map,或者如果它是我的組件的一部分,我還應該在哪里包含它? 我只是想瀏覽一下成分並展示它們。 謝謝你的幫助 ] 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;
這是因為您的組件在異步調用完成之前已呈現/掛載。
如果你改變:
recipe.ingredients.map(ingredient => {
對此:
recipe.ingredients && recipe.ingredients.map(ingredient => {
它應該像你想要的那樣工作。
這是因為除非存在成分,否則不會調用 map。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.