React.js中如何映射渲染包含对象的嵌套数组且支持组件化扩展?
你原有代码的问题是Content组件的map遍历只执行了log打印,没有返回要渲染的Part组件。你可以按分层组件的思路实现,不需要手动处理动态索引,直接用数组本身的层级嵌套遍历即可,同时复用组件满足后续新增课程的扩展需求:
完整组件实现
// 单个课时组件:渲染单条课时的名称和练习数 const Part = (props) => { return <div> {props.part.name}:{props.part.exercises} 道练习题 </div> } // 课程内容组件:遍历单门课程下的所有课时 const Content = (props) => { return( <div style={{paddingLeft: '16px'}}> {props.parts.map(part => <Part part={part} key={part.id} />)} </div> ) } // 单门课程组件:渲染课程名称 + 对应课程内容 const Course = (props) => { return ( <div style={{margin: '20px 0'}}> <h3>{props.course.name}</h3> <Content parts={props.course.parts} /> </div> ) } // 顶层课程列表组件:遍历所有课程 const CourseList = (props) => { return ( <div> <h2>全部课程</h2> {props.courses.map(course => <Course course={course} key={course.id} />)} </div> ) }
调用方式
在业务组件(比如App组件)中传入你定义的课程数组即可:
// 你定义的课程数组 const courses = [ { name: 'Half Stack application development', id: 1, parts: [ { name: 'Fundamentals of React', exercises: 10, id: 1 }, { name: 'State of a component', exercises: 14, id: 3 }, { name: 'Redux', exercises: 11, id: 4 } ] }, { name: 'Node.js', id: 2, parts: [ { name: 'Routing', exercises: 3, id: 1 }, { name: 'Middlewares', exercises: 7, id: 2 } ] } ] function App() { return <CourseList courses={courses} /> }
该实现天然支持扩展,后续新增课程只需要在顶层courses数组中新增符合格式的课程对象即可,不需要修改组件逻辑。列表渲染的key直接使用每项自带的唯一id,无需手动维护索引,避免数组变更后索引混乱的问题。
内容的提问来源于stack exchange,提问作者Kristian Husso
相关产品推荐
相关产品推荐

