React使用forEach遍历渲染时间轴组件子组件未触发问题咨询
问题根本原因
Array.prototype.forEach 方法执行后返回值为undefined,不会返回你在回调中定义的组件,因此JSX中没有接收到任何要渲染的子元素,TimelineContainer自然不会被实例化执行,这和组件定义方式无关,你的两种组件写法都是符合React规范的。
修复方案
- 将遍历方法从
forEach替换为map,map会返回由回调返回值组成的新数组,React可以正常渲染该数组中的组件 - 给遍历生成的
TimelineContainer添加唯一key属性,避免React抛出列表渲染告警 - 重命名你自定义的根组件,避免和第三方包的
Timeline组件重名导致引用冲突
修复后核心代码示例
// 将自定义组件重命名避免和第三方Timeline冲突 export default function HistoryTimeline() { // call to server for data which is saved to results.data.history const history = results.data.history return ( <Timeline theme={customTheme} dateFormat='ll'> {/* 把forEach改成map */} {Object.keys(history).map(startDate => { console.log(startDate) // 增加唯一key属性 return ( <TimelineContainer key={startDate} startDate={startDate} sections={history[startDate]} /> ) })} </Timeline> ) }
额外优化提示
key是React的特殊属性,不会传递到组件内部的props中,如果你在TimelineSection内部需要用到唯一标识,需要单独传自定义属性(比如sectionId={xxx})接收。
内容的提问来源于stack exchange,提问作者StudiousProgrammer
相关产品推荐
相关产品推荐

