You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React向子组件传递对象数组报错:arr.map is not a function

问题解决:React子组件调用map时报错"arr.map is not a function"

你的问题出在子组件接收props的方式错误。React组件的props是一个包含所有传递属性的单一对象,不是分开的独立参数。

看你的子组件代码:

const RecipeListContainer = (title, recipeSample) => {

这里的title其实是整个props对象,recipeSample是undefined——因为你只传了一个参数(props对象),第二个参数自然不存在。所以调用recipeSample.map()时,本质是在undefined上调用map,就会报"map is not a function"的错误。

修正方法:

把子组件的参数改成接收props对象,然后从中取出需要的属性:

import React from 'react'
import classes from './recipeListContainer.module.scss'

const RecipeListContainer = (props) => {
  return (
    <div className={classes.container}>
        <h1 className={classes.listTitle}>{props.title}</h1>
        {props.recipeSample.map((recipe) => (
            <div key={recipe.id} className={classes.recipeCard}>
                <div className={classes.recipeImage}></div>
                <div className={classes.recipeDescription}>
                    <h4>{recipe.title}</h4>
                    <p>{recipe.category}</p>
                    <p>Created by : {recipe.author}</p>
                    <button type="button">Remove from menu</button>
                </div>
            </div>
        ))}
    </div>
  )
}

export default RecipeListContainer

更简洁的写法(解构props):

你也可以直接在参数里解构props,代码会更清爽:

const RecipeListContainer = ({ title, recipeSample }) => {
  return (
    <div className={classes.container}>
        <h1 className={classes.listTitle}>{title}</h1>
        {recipeSample.map((recipe) => (
            <div key={recipe.id} className={classes.recipeCard}>
                <div className={classes.recipeImage}></div>
                <div className={classes.recipeDescription}>
                    <h4>{recipe.title}</h4>
                    <p>{recipe.category}</p>
                    <p>Created by : {recipe.author}</p>
                    <button type="button">Remove from menu</button>
                </div>
            </div>
        ))}
    </div>
  )
}

这样修改后,子组件就能正确拿到父组件传递的recipeSample数组,调用map就不会报错了。

内容的提问来源于stack exchange,提问作者Danil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:45:48