React应用出现`thumb-undefined`重复key警告,求排查解决
React时间滑块重复key警告排查与解决
问题描述
开发时间滑块功能时,控制台持续抛出重复key警告:
bundle.js:21658 Warning: Encountered two children with the same key, `thumb-undefined`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
问题原因
你在renderThumb回调中尝试用idx生成唯一key,但回调参数顺序错误,导致idx未被正确赋值为索引,最终得到undefined,两个滑块thumb的key都变成thumb-undefined,触发重复key警告。
以常见的滑块组件(如react-range)为例,renderThumb的回调参数顺序为(thumbProps, state, index),你当前的写法把索引参数放在了第二个位置,实际拿到的不是有效索引值。
解决方案
调整renderThumb的参数顺序,正确获取索引值:
修改后的renderThumb代码片段:
renderThumb={({ props, isDragged }, state, idx) => { const { key, ...restProps } = props; return ( <div key={`thumb-${idx}`} {...restProps} style={{ ...restProps.style, height: '24px', width: '24px', borderRadius: '50%', backgroundColor: 'var(--primary-color)', display: 'flex', justifyContent: 'center', alignItems: 'center' }} > <div style={{ height: '16px', width: '5px', backgroundColor: isDragged ? 'var(--primary-color)' : '#CCC' }} /> </div> ); }}
额外说明
- 务必对照你使用的Range组件官方文档,确认
renderThumb的回调参数定义,保证索引参数的位置正确。 - 你当前通过
const { key, ...restProps } = props;剥离原key属性的做法是正确的,避免了组件内部key与自定义key冲突。
内容的提问来源于stack exchange,提问作者econobro
相关产品推荐
相关产品推荐

