【问题标题】:'recipe' is not defined when mapping a array映射数组时未定义“配方”
【发布时间】:2021-04-09 20:46:57
【问题描述】:

我目前正在尝试显示我的信息烧瓶 API,它正在返回 json 数据。

运行以下代码时出现错误:

第 37:61 行:'recipe' 未定义 no-undef
第 41:24 行:'recipe' 未定义 no-undef
第 42:24 行:'recipe' 未定义 no-undef

这是它获取的数据: https://pastebin.com/uYUuRY6U

代码如下:

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

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.
          mealplanIngredients: [], // Ingredents of the recipe
      }
  }

  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"])
        })
    }).catch(error => {
        console.log("mealplan-detail GET Error ", error)
    })
  }

  componentDidMount() {
      this.getMealplanItem();
  }

  render() {
      const renderRecipes = this.state.mealplanRecipes.map((recipe, idx => {
          return (
              <div key={idx}>
                  <h1>
                      {recipe.recipe_name}
                      {recipe.recipe_dificulty}
                  </h1>
              </div>
          )
      }))
      return (
          <div>
              <NavBar/>
              <Featured/>
              {renderRecipes}
          </div>
      )
  }
}

【问题讨论】:

    标签: reactjs array.prototype.map


    【解决方案1】:

    你的括号是错误的,map函数的参数应该在自己的括号中。所以改成这样:

      const renderRecipes = this.state.mealplanRecipes.map((recipe, idx) => {
          return (
              <div key={idx}>
                  <h1>
                      {recipe.recipe_name}
                      {recipe.recipe_dificulty}
                  </h1>
              </div>
          )
      })
    

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 2020-10-31
      • 2019-01-23
      • 2021-11-02
      • 2021-04-09
      • 2021-07-25
      相关资源
      最近更新 更多