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

时间:2020-01-03 17:57:39

标签: javascript arrays reactjs

我是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;

1 个答案:

答案 0 :(得分:1)

这是因为在异步调用完成之前就已渲染/装入了组件。

如果您更改:

recipe.ingredients.map(ingredient => {

对此:

recipe.ingredients && recipe.ingredients.map(ingredient => {

它应该可以根据需要工作。

这是因为除非存在成分,否则地图不会被调用。