reactjs - 当我尝试将道具传递给孩子时映射不是函数错误
问题描述
我被困住了,不知道这里发生了什么:
这是子组件的代码:
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)
解决方案
{0: {…}, 1: {…}, 2: {…}}
这不是一个数组,它是一个对象。组件道具表示为一个对象。对象上没有地图功能。
如何解决它取决于您,但我会将卡片作为道具传递给 FrontCard 组件。
<FrontCard cards={this.state.cards} />
然后你可以像这样在道具上调用地图。
this.props.cards.map((card, index) => ..
推荐阅读
- php - 默认的 www.conf 总是出现在 /etc/php-fpm.d/ 中,所以我的主网站 .conf 文件由于相同的端口而变得混乱,我该如何解决这个问题?
- angular - 模块化 Angular 架构可最大限度地重用代码,但仍提供足够的灵活性
- php - 如何修复 Laravel“此路线不支持 Post 方法”?
- c - 将循环中创建的子 pid 分配给数组
- php - 是否有 wordpress 功能来检测插件是否不是最新的?
- javascript - SetimeOut 间隔因“无法将未定义或空值转换为对象”而失败
- ibm-cloud-infrastructure - 如何将关联的 VLAN 子网路由到我在 SoftLayer 上的 Vyatta?
- azure - az:错误:无法识别的参数:--query loginServer
- windows - Windows 调度程序——公平时间切片如何工作?
- java - 我有一个用户类,它有一个私有字段 ArrayList