React JS中map函数使用问题:无法循环渲染组件求解
React中map循环渲染ProductItems组件失败的解决方案
问题根源
- 数据结构层级错误:导出的
blog是外层数组,实际需要循环的列表数据是该数组内对象的blog属性,直接遍历外层数组只会渲染一次空内容。 - 组件未接收props:
ProductItems组件未定义props参数,无法获取父组件传递的数据源。 - 卡片内容未动态绑定:当前卡片标题、文本均为硬编码占位内容,未使用传入的真实数据。
修复步骤及代码
1. 修正数据源遍历逻辑
两种可选方案:
方案一:调整数据结构(推荐)
修改blog.jsx,直接导出需要循环的数组,去掉多余外层嵌套:
export let blog = [ { "userId": 1, "id": 1, "title": "are or do repels provide blacked out to accept the option criticizes", "body": "because and accepts\naccepts the result of refusal convenient and when which is all\nof our things, but they are the thing that will happen to the architect" }, { "userId": 1, "id": 2, "title": "who is to be", "body": "is of things at the time of life\nthey are nothing to follow let the pain of the blessed rebuke those pains and not run away from the caresses of the pleasure, nor any trouble" }, // 其余数据项保持不变 ]
方案二:直接遍历内层数组
若不想修改数据结构,在App.js中直接访问内层数组:
<Container> <Row> {blog[0].blog.map((item) => ( <ProductItems key={item.id} item={item}/> ))} </Row> </Container>
注意:使用数据的唯一id作为key,避免React渲染性能问题,不要用索引i。
2. 修改ProductItems组件接收并渲染动态数据
给组件添加props参数,替换占位内容为传入的真实数据:
function ProductItems({ item }) { return ( <Col lg="3" md="6" className="mb-4"> <Card> {/* 使用picsum生成对应id的图片,替换占位符 */} <Card.Img variant="top" src={`https://picsum.photos/id/${item.id}/200/180`} /> <Card.Body> <Card.Title>{item.title}</Card.Title> <Card.Text> {/* 截取部分文本避免卡片过长 */} {item.body.substring(0, 100)}... </Card.Text> <Button variant="primary">Go somewhere</Button> </Card.Body> </Card> </Col> ); }
3. 完整修复后的App.js示例
import { Container, Row, Col, Card, Button } from 'react-bootstrap'; import { blog } from './blog'; function ProductItems({ item }) { return ( <Col lg="3" md="6" className="mb-4"> <Card> <Card.Img variant="top" src={`https://picsum.photos/id/${item.id}/200/180`} /> <Card.Body> <Card.Title>{item.title}</Card.Title> <Card.Text> {item.body.substring(0, 100)}... </Card.Text> <Button variant="primary">Go somewhere</Button> </Card.Body> </Card> </Col> ); } function App() { return ( <Container className="mt-4"> <Row> {blog.map((item) => ( <ProductItems key={item.id} item={item}/> ))} </Row> </Container> ); } export default App;
内容的提问来源于stack exchange,提问作者Mohammad Omer Abbasi
相关产品推荐
相关产品推荐

