首页 > 解决方案 > 获取“TypeError:无法读取未定义的属性'map'”

问题描述

当我尝试运行我的代码时,它显示此错误:无法读取未定义的属性“地图”

这是我的代码:

import React, { Component } from 'react';
import Recipe from './Recipe';
import RecipeSearch from './RecipeSearch';

export default class RecipeList extends Component {
    render() {
        const { recipes } = this.props;
        return (
                <React.Fragment>
                    <RecipeSearch />
                    <div className="container my-5" >
                        {/*title*/ }
                        <div className="row">
                            <div className="col-10 mx-auto col-md-6 text-center text-uppercase mb-3">
                                <h1 className="text-slanted">recipe list</h1>
                            </div>
                        </div>
                    {/*end of title*/}
                        <div className="row">
                            {recipes.map(recipe =>{
                                return <Recipe key={recipe.recipe_id}
                                recipe={recipe}/>;  
                            })}
                        </div>
                    </div>
                </React.Fragment>
            );
    }
}

那么我该如何解决呢?

标签: reactjs

解决方案


问题是由于您的recipes道具是undefined.

你应该经常检查你是否在你的props,

{recipes && recipes.length > 0 && recipes.map(recipe =>{
       return <Recipe key={recipe.recipe_id} recipe={recipe}/>;  
})}

推荐阅读