React中如何仅渲染JSON数组指定索引位置的单个数据?
解决方案:仅渲染React数组中指定索引的单个数据
直接通过数组索引(如todos[0])获取目标元素,替换原有的遍历逻辑,同时用卡片组件包裹内容实现突出展示,以下是修改后的完整代码及关键说明:
修改后的组件代码
import { useState, useEffect } from 'react'; import { Typography, Card, CardContent } from '@mui/material'; import useStyles from './your-styles-file'; // 保留你的样式文件引用 export default () => { const classes = useStyles(); const url = "Datos.json"; // 初始值设为空数组,避免undefined判断问题 const [todos, setTodos] = useState([]); const fetchApi = async () => { const response = await fetch(url); const responseJSON = await response.json(); setTodos(responseJSON); }; useEffect(() => { fetchApi(); }, []); // 处理加载/数组为空的情况 if (!todos.length) { return <div>Cargando...</div>; } // 取指定索引的元素,这里是索引0,可按需修改为其他索引 const featuredTodo = todos[0]; // 格式化时间(简化冗余逻辑) const date = new Date(featuredTodo.dt * 1000); const hours = `0${date.getHours()}`.slice(-2); const minutes = `0${date.getMinutes()}`.slice(-2); const formattedTime = `${hours}:${minutes}`; return ( // 用Card组件包裹实现突出展示,可自定义样式 <Card className={classes.featuredCard}> <CardContent> <Typography variant="subtitle1">{featuredTodo.Competicion}:</Typography> <Typography variant="h4" gutterBottom> {formattedTime} {featuredTodo.Partido} </Typography> <Typography variant="body1" gutterBottom> 场次编号: {featuredTodo.Partido} </Typography> <OldButtons {...featuredTodo} /> </CardContent> </Card> ); };
关键修改说明
- 替换遍历逻辑:移除
todos.map循环,直接通过索引[0]获取目标元素;若需要展示前2个元素,可改用todos.slice(0,2)再遍历 - 优化状态初始化:将
useState()改为useState([]),避免初始状态为undefined导致的判断异常 - 增加安全判断:用
todos.length判断数组是否有数据,防止数组为空时访问todos[0]报错 - 简化时间格式化:删除冗余的
dta数组,直接用变量存储格式化后的时间,代码更简洁 - 卡片包裹内容:用Material-UI的
Card+CardContent组件包裹内容,实现突出展示的视觉效果 - 修正字段匹配:你的JSON数据中不存在
evento字段,将代码中todo.evento替换为实际存在的Partido字段
内容的提问来源于stack exchange,提问作者MatiST00
相关产品推荐
相关产品推荐

