React DnD拖拽系统中重复Key错误及Item ID重复生成问题求助
React DnD拖拽系统中重复Key错误及Item ID重复生成问题求助
我现在在用React DnD开发一个拖拽放置系统,遇到了个棘手的问题,想请教各位大佬帮忙分析下。
我的拖拽组件里,原本是在useDrag的配置回调里生成唯一ID作为item的属性,代码如下:
function DragElements({type}:{ type:typeof dragAbleTypes[keyof typeof dragAbleTypes]}) { const [{isdragging},drag] = useDrag(()=>{ return { type:type, item:{id:uuid(),type:type}, collect:(e)=>{ return {isdragging:!!e.isDragging()} } } }) return ( // @ts-ignore <div ref={drag}> {type} </div> ) } export default DragElements
然后在放置组件中,我通过useDrop接收拖拽过来的item,把它添加到状态数组里:
function Canvas() { const [elements, setElements] = useAtom(editorState) const [,drop] = useDrop(()=>({ accept:Object.values(dragAbleTypes), drop:(item:{id:UUIDTypes,type:string}, monitor)=>{ console.log(item.id); const newElement = { id:item.id, type:item.type } setElements(e=>[...e,newElement]) } })) return ( // @ts-ignore <div className='h-screen flex flex-col border w-full 'ref={drop}> {elements.map(e=>{ console.log("key:",e.id); return(<EditorRenderingHelper key={e.id.toString()} element = {e}/>) })} </div> ) } export default Canvas
现在遇到的问题很奇怪:
- 第一次拖拽放置是正常的,但第二次及之后的拖拽,控制台打印的
item.id始终是第一次生成的那个ID - 每次添加新元素到
elements数组后,遍历数组打印key时,所有元素的ID全是同一个,日志如下:
key: 98f499f3-f214-401d-90ce-a069c7396a34 key: 98f499f3-f214-401d-90ce-a069c7396a34 key: 98f499f3-f214-401d-90ce-a069c7396a34 key: 98f499f3-f214-401d-90ce-a069c7396a34
同时浏览器控制台还抛出了重复Key的错误提示:
Encountered two children with the same key, `f1ff56c1-0b2e-4f4c-9ba5-6c1568714635`. 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.
我实在搞不懂,明明每次拖拽都应该重新生成新的UUID才对,为什么每次拿到的都是同一个ID?求大家帮忙看看问题出在哪了😭
备注:内容来源于stack exchange,提问作者Kushal
相关产品推荐
相关产品推荐

