【问题标题】:Issue rendering Item list in react在反应中问题渲染项目列表
【发布时间】:2017-10-09 11:43:23
【问题描述】:

我正在尝试在屏幕上呈现项目列表,但出现错误:

Cannot read property 'map' of undefined

我的代码中缺少什么/做错了什么?

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

const RecipeList = ({recipes}) => {

    const Items = recipes.map((recipe) => {
      return <RecipeListItem key={recipe.id} recipe={recipe} />
    });

    return (
        <div>
            {Items}
        </div>
    )
}

export default RecipeList

【问题讨论】:

  • recipes 在哪里定义?组件如何接收该数据?如果你console.log(recipes) 会发生什么?
  • 我猜测父组件将 recipes 作为其状态的道具传递 - 您是否在父状态中定义了 recipes
  • 是的。我在 App.js 的构造函数中定义了食谱,然后我有 但我看到我没有将状态传递给该组件。我尝试像 一样传递它,但它不起作用。
  • 使它能够将 recipes.recipes 添加到我的地图功能:const Items = re.recipes.map((recipe) =&gt; { return &lt;RecipeListItem key={recipe.id} recipe={recipe} /&gt; });

标签: reactjs


【解决方案1】:

我强烈建议不要将整个父状态传递给子状态 - 像这样设置它:

App.js 中,像这样传递道具:

<RecipeList recipes={this.state.recipes} />

那么就在child中引用props——

const RecipeList = (props) => {

    const Items = props.recipes.map((recipe) => {
      return <RecipeListItem key={recipe.id} recipe={recipe} />
    });

    return (
        <div>
            {Items}
        </div>
    )
}

export default RecipeList

【讨论】:

  • 非常感谢。在我的代码中,我引用的不是道具而是 {recipes}:const RecipeList = ({recipes}) =&gt; { 什么是最佳做法?
  • 没有。实际上,当我使用 {recipes} 之类的解构时,我最终会很好地工作:const Items = recipes.map((recipe) =&gt; {
  • 对不起,我误解了你之前的评论。我只是重申一点,不要将整个父状态传递给孩子。
  • 我个人的偏好是不经常使用解构,因为它不那么明确。
猜你喜欢
  • 1970-01-01
  • 2018-01-07
  • 2021-04-14
  • 2019-12-05
  • 2016-07-13
  • 2021-04-13
  • 2018-01-25
  • 1970-01-01
相关资源
最近更新 更多