【问题标题】:TypeError: Cannot read property 'map' of undefined When trying to map multiple arraysTypeError:尝试映射多个数组时无法读取未定义的属性“映射”
【发布时间】:2021-04-09 21:57:35
【问题描述】:

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

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

尝试以下代码时

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 返回中的格式。我是地图新手,不知道是否有解决方法或更好的方法。

【问题讨论】:

  • 从来没有定义过this.state.recipes。即使在安装数据获取之后也不会。那应该是什么?

标签: reactjs array.prototype.map


【解决方案1】:

从来没有定义过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) => {...

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

【讨论】:

    【解决方案2】:

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

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

    请参考下面代码中我的cmets。

    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>
        );
      }
    }

    【讨论】:

      猜你喜欢
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2021-08-05
      相关资源
      最近更新 更多