无法读取React和API中未定义的属性“ map”

时间:2019-11-02 20:40:26

标签: reactjs api

我是一个非常新的反应者,我正在尝试从food2fork api导入数据,但出现错误

  

TypeError:无法读取未定义的属性“ map”

如果我撤消此代码,则错误为无。此代码是主要地方会发生错误

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

RecipeList.js

的整页
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 />
                <h1>Recipe List</h1>
                <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 title */}
                    <div className="row">
                        {recipes.map (recipe => {
                            return <Recipe key={recipe.recipe_id} recipe={recipe}
                            />;
                        })}
                    </div>
                </div>

                <Recipe />
            </React.Fragment>
        );
    }
}

App.js中:

render(){
    console.log(this.state.recipes);

    return (
      <React.Fragment>
        <RecipeList />
        <RecipeDetails />
      </React.Fragment>
    );
 }

2 个答案:

答案 0 :(得分:1)

我认为您将食谱数据保留在App.js的this.state.recipes

您需要将其作为道具传递给<RecipeList组件,以在那里用作道具。

所以在您的App.js中只需执行

render(){
  console.log(this.state.recipes);

  return (
    <React.Fragment>
      <RecipeList recipes={this.state.recipes}  />
      <RecipeDetails />
    </React.Fragment>
  );
}

答案 1 :(得分:1)

首先,您没有将任何道具传递给RecipeList。
在App.js中更改

 return (
      <React.Fragment>
        <RecipeList recipes={this.state.recipes} />
        <RecipeDetails />
      </React.Fragment>
    );

其次,在RecipeList.js中,仅在异步功能完成时才呈现它。
更改:

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

收件人:

{recipes ? recipes.map (recipe => {
  return <Recipe key={recipe.recipe_id} recipe={recipe}
    />;
  }) : null
}}