React组件中map函数调用报错:data.map is not a function求助
解决React中map函数无法遍历数组的问题
错误原因分析
你遇到的Uncaught TypeError: data.map is not a function错误,核心由以下几个问题导致:
- props传递与接收不匹配:App组件传递给Ptot的是一个包含
props属性的对象,而非直接的数组。React组件接收的props是聚合所有传入属性的对象,所以Ptot里的props实际是{ props: Produits },导致data变成对象,无法调用map方法。 - map函数无返回值:Ptot组件中
map的箭头函数用了大括号{}但未显式返回JSX元素,导致没有渲染任何内容。 - 子组件props接收方式错误:Prot组件直接把接收的props当作element对象使用,但实际它接收的是包含
element属性的props对象。 - 列表缺少唯一key:React渲染列表时要求每个元素有唯一
key属性,你的数组中存在重复id,需要修正。
修正后的代码
App.js
import React from "react"; import Ptot from "./Ptot"; const Produits=[ { id:1, title:"pc pourtable hp", prix:'7490', image:"" }, { id:2, title:"pc pourtable delet", prix:'8990', image:"" }, { id:3, // 修正重复id title:"pc pourtable infnx", prix:'6590', image:"" } ]; function App(){ return( <div> hello {/* 用语义化属性名传递数组 */} <Ptot produits={Produits} /> </div> ) } export default App;
Ptot.js
import React from "react"; import Prot from './Prot.js' import { useState } from "react"; // 解构出传递的数组 function Ptot({ produits }){ const [data, setData] = useState(produits) return ( <div className="container"> <div> { data.map((elm) => ( // 显式返回组件并添加唯一key <Prot key={elm.id} element={elm} /> )) } </div> </div> ) } export default Ptot;
Prot.js
import React from "react"; // 解构props中的element属性 function Prot({ element }) { return ( <div> <p>hello</p> <div> <div className="col"> <div className="cart-shadow-sm"> <img className="bd-placeholder-img card-img-top" src={`image/${element.image}`} alt={element.title} /> <div className="card-body"> <p className="card-title">{element.title}</p> <p className="card-text">{element.prix}</p> <div className="d-flex justify-content-between align-items-center"> {/* 修正拼写错误 */} <div className="btn-group"> <button type="button" className="btn btn-sm btn-outline-secondary">Ajoute un panier</button> {/* 修正拼写错误 */} </div> </div> </div> </div> </div> </div> </div> ) } export default Prot;
额外修正说明
- 修正了数组中重复的
id,避免React列表渲染警告。 - 修正了Prot组件中
justify-conten-between的拼写错误,改为justify-content-between。 - 修正了按钮文本中的拼写错误
paner为panier。 - 给图片添加了有意义的
alt属性,提升可访问性。
内容的提问来源于stack exchange,提问作者Ahmed_Aboutalib
相关产品推荐
相关产品推荐

