TypeError: Cannot read property 'map' of undefined When trying to map multiple arrays

TypeError: Cannot read property 'map' of undefined When trying to map multiple arrays

我正在尝试同时映射多个数组,但我不确定您是不是这样做的。我收到错误

TypeError: Cannot read property 'map' of undefined

尝试以下代码时

import React, { Component } from 'react';
import Axios from 'axios';
import NavBar from '../header-footer/nav-bar'
import Featured from './FeaturedMealplan'
import RecipeItem from './RecipeItem'

export default class MealPlanDetail extends Component {
  constructor(props) {
      super(props);

      this.state = {
          currentId: this.props.match.params.slug,
          mealplanItem: {}, // Full mealplan
          mealplanRecipes: [], // Contains recipe names and difficulty.
      }
  }

  getMealplanItem() {
    Axios.get(`http://localhost:5000/get-mealplan/${this.state.currentId}`
    ).then(response => {
        console.log("response", response)
        this.setState({
            mealplanItem: response.data.mealplan,
            mealplanRecipes: this.state.mealplanRecipes.concat(response.data.mealplan["recipes"]),
            mealplanIngredients: this.state.mealplanIngredients.concat(response.data.mealplan["recipe_info"]),
            recipeItem: response.data.mealplan.recipes
        })
    }).catch(error => {
        console.log("mealplan-detail GET Error ", error)
    })
  }

  componentDidMount() {
      this.getMealplanItem();
  }

  render() {
      const renderRecipe = this.state.recipes.map((recipe, idx) => {
          return (
              <div key={idx}>
                  <h1>{recipe.recipe_name}</h1>
                  <h2>Recipe Difficulty: <span>{recipe.recipe_dificulty}</span></h2>
                  <div>
                    <RecipeItem recipeItem={this.state.recipeItem} />
                  </div>
              </div>
          )
      })
      return (
          <div>
              <NavBar/>
              <Featured/>
              {renderRecipe}
          </div>
      )
  }
}

给出的数据:https://pastebin.com/uYUuRY6U

我只需要能够正确地格式化它,这就是我希望它在 renderRecipe return 中格式化的方式。我是地图新手,不知道有没有办法解决或者有更好的方法。

我们可以改进的代码中的一些问题:

  1. this.state.recipes 在您的逻辑中似乎未定义。是打错了吗?
  2. 我建议将 renderRecipe 作为函数而不是变量来实现。
  3. 你只希望在有数据的时候渲染renderRecipe,但是当你的组件被挂载时,this.state.recipes是未定义的。它只有在 getMealplanItem 获得响应并在回调中定义时才有价值。所以你应该在渲染之前检查该值是否被定义。

请参考我在下面代码中的注释。

import React, { Component } from "react";
import Axios from "axios";
import NavBar from "../header-footer/nav-bar";
import Featured from "./FeaturedMealplan";
import RecipeItem from "./RecipeItem";

export default class MealPlanDetail extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // ... define `recipes` if that's what you want
    };
  }

  getMealplanItem() {
    Axios.get(`http://localhost:5000/get-mealplan/${this.state.currentId}`)
      .then((response) => {
        console.log("response", response);
        // ... set state `recipes` here if that's what you want
        this.setState({
          mealplanItem: response.data.mealplan,
          mealplanRecipes: this.state.mealplanRecipes.concat(
            response.data.mealplan["recipes"]
          ),
          mealplanIngredients: this.state.mealplanIngredients.concat(
            response.data.mealplan["recipe_info"]
          ),
          recipeItem: response.data.mealplan.recipes
        });
      })
      .catch((error) => {
        console.log("mealplan-detail GET Error ", error);
      });
  }

  componentDidMount() {
    this.getMealplanItem();
  }

  render() {
    const renderRecipe = () => {
      // change renderRecipe from a variable to a function
      if (!this.state?.recipes) {
        // check whether `recipes` is a defined value
        return null;
      }
      return this.state.recipes.map((recipe, idx) => {
        return (
          <div key={idx}>
            <h1>{recipe.recipe_name}</h1>
            <h2>
              Recipe Difficulty: <span>{recipe.recipe_dificulty}</span>
            </h2>
            <div>
              <RecipeItem recipeItem={this.state.recipeItem} />
            </div>
          </div>
        );
      });
    };
    return (
      <div>
        <NavBar />
        <Featured />
        {renderRecipe()}  // it's a function call now
      </div>
    );
  }
}

从未定义过 this.state.recipes。基于数据类型和注释

this.state = {
  currentId: this.props.match.params.slug,
  mealplanItem: {}, // Full mealplan
  mealplanRecipes: [], // Contains recipe names and difficulty.
}

我假设你的意思是 this.state.mealplanRecipes

然后你的渲染变成

const renderRecipe = this.state.mealplanRecipes.map((recipe, idx) => {...

这可以轻松处理空数组的初始渲染。