React组件存入数组时仅首个组件初始化问题排查
React组件数组仅首个组件初始化问题
问题场景
我在应用中有Component1和Component2两个组件,还有负责渲染它们的RenderingComponent。在RenderingComponent的根层级定义了包含这两个组件选项的数组,代码如下:
const RenderingComponent = () => { const ref1 = useRef(); const ref2 = useRef(); const array = [{ title: '#1', component: <Component1 ref={ref1} />, // 其他属性 }, { title: '#2', component: <Component2 ref={ref2} /> // 其他属性 }]; // 后续渲染逻辑 }
问题现象
- 仅数组中的第一个组件会被初始化,调换数组顺序后,原第二个组件会初始化而第一个不会;
- 在两个组件的根层级添加
console.log,仅首个组件的日志会输出; - 数组中第二个组件对应的
ref.current始终为undefined。
补充:两个组件均使用forwardRef + useImperativeHandle暴露方法。
原因分析
核心问题在于你只是创建了组件元素并存入数组,但并没有实际渲染数组中所有的组件元素。
React组件只有在被挂载到DOM树中时才会执行初始化逻辑(包括console.log执行、ref被赋值)。如果后续渲染逻辑只处理了数组的第一个元素(比如仅渲染array[0].component),那自然只有第一个组件会被初始化,第二个组件元素从未被挂载,所以ref始终是undefined,也不会输出日志。
解决方法
确保你在RenderingComponent中渲染数组里的所有组件元素,比如用map循环渲染:
const RenderingComponent = () => { const ref1 = useRef(); const ref2 = useRef(); const array = [{ key: 'comp1', title: '#1', component: <Component1 ref={ref1} />, }, { key: 'comp2', title: '#2', component: <Component2 ref={ref2} /> }]; return ( <div> {/* 循环渲染所有组件 */} {array.map(item => ( <div key={item.key}> <h3>{item.title}</h3> {item.component} </div> ))} </div> ); }
这样两个组件都会被挂载到DOM中,各自的初始化逻辑会执行,ref也能正确赋值。
内容的提问来源于stack exchange,提问作者ThomasSquall
相关产品推荐
相关产品推荐

