首页 > 解决方案 > 当我尝试将道具传递给孩子时映射不是函数错误

问题描述

我被困住了,不知道这里发生了什么:

这是子组件的代码:

import React, { Component } from "react";
import { ErrorBoundary } from "../../utils/ErrorBoundary";

class FrontCard extends Component {
  render() {
    return (
      <div>
        {console.log(this.props)}{" "}
        {this.props.map((card, index) => (
          <Card key={index} style={{ width: "18rem" }}>
            <Card.Img variant="top" src="holder.js/100px180" />
            <Card.Body>
              <Card.Title>{card.title}</Card.Title>
              <Card.Text>{card.body} </Card.Text>
              <Button variant="primary">Go somewhere</Button>
            </Card.Body>
          </Card>
        ))}
      </div>
    );
  }
}

export default FrontCard;

这就是它的名称:

        <FrontCard {...this.state.cards} />

如您所见,我在映射之前记录了道具,并且该数组在控制台中:

{0: {…}, 1: {…}, 2: {…}}

问题是,为什么说 map 不是函数?

Uncaught TypeError: this.props.map is not a function
    at FrontCard.render (FrontCard.jsx:44)

标签: reactjs

解决方案


{0: {…}, 1: {…}, 2: {…}}

这不是一个数组,它是一个对象。组件道具表示为一个对象。对象上没有地图功能。

如何解决它取决于您,但我会将卡片作为道具传递给 FrontCard 组件。

 <FrontCard cards={this.state.cards} />

然后你可以像这样在道具上调用地图。

this.props.cards.map((card, index) => ..

推荐阅读