如何遍历JSON数据仅提取RED节点内容并在ReactJS中展示
React 遍历展示 Registered_Courses.RED 数据实现方案
你拿到的源数据外层包裹了一层数组结构,首先需要正确提取RED字段下的课程数组:const redCourses = Registered_Courses[0].RED,之后直接用数组的map方法遍历渲染即可。
完整示例代码
import React from 'react'; // 你的源数据 const Registered_Courses = [ { RED: [ { course_Name: 'Programming Fundamentals', course_Code: 'SODV110', start_Date: '2021-10-10', end_Date: '2022-10-11', Fees: '$1300', Delivery_Mode: 'In Class Learning', Description: 'Computer programming is central to software development.', }, { course_Name: 'Programming Fundamentals', course_Code: 'SODV110', start_Date: '2021-10-10', end_Date: '2022-10-11', Fees: '$1300', Delivery_Mode: 'In Class Learning', Description: 'Computer programming is central to software development.', }, ], NESS: [ { course_Name: 'Programming Fundamentals', course_Code: 'SODV110', start_Date: '2021-10-10', end_Date: '2022-10-11', Fees: '$1300', Delivery_Mode: 'In Class Learning', Description: 'Computer programming is central to software development.', }, ], }, ]; function RedCourseList() { // 提取RED下的全部课程数据 const redCourses = Registered_Courses[0].RED; return ( <div style={{maxWidth: '800px', margin: '20px auto'}}> <h2>RED 已注册课程列表</h2> {redCourses.length === 0 ? ( <p>暂无RED分类下的课程</p> ) : ( redCourses.map((course, index) => ( // 实际项目中如果课程有唯一id,建议替换index为id作为key值 <div key={index} style={{border: '1px solid #e5e7eb', borderRadius: '8px', padding: '16px', marginBottom: '16px'}}> <h3>{course.course_Name}({course.course_Code})</h3> <ul style={{listStyle: 'none', paddingLeft: 0}}> <li>开课时间:{course.start_Date}</li> <li>结课时间:{course.end_Date}</li> <li>课程费用:{course.Fees}</li> <li>授课模式:{course.Delivery_Mode}</li> <li>课程简介:{course.Description}</li> </ul> </div> )) )} </div> ); } export default RedCourseList;
注意事项
- React 渲染列表时必须给每一项加唯一的
key属性,上述示例用了索引作为临时key,实际项目中替换为课程专属唯一标识字段可避免渲染异常。 - 如果
Registered_Courses是通过接口请求获取的异步数据,记得添加加载状态判断,避免数据还没返回时取值报错。
内容的提问来源于stack exchange,提问作者Agyapal Dhanoa
相关产品推荐
相关产品推荐

