gpt4 book ai didi

javascript - 在 React 中渲染 array.map() 时出错

转载 作者:行者123 更新时间:2023-12-02 22:10:15 24 4
gpt4 key购买 nike

我对 React 非常陌生,这可能是一个愚蠢的问题,但我收到一条错误消息:Uncaught TypeError: Cannot read property 'map' of undefined
当我尝试显示每个食谱的成分时。我不确定是否可以在 return 语句中使用 array.map,或者如果它是我的组件的一部分,我还应该在哪里包含它?我只是想检查一下成分并展示它们。感谢您的帮助![Screenshot of my console ] 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 。

关于javascript - 在 React 中渲染 array.map() 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59583177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com