React美丽的DND - 我得到"无法找到id为1的可拖动元素"
React美丽的DND - 我得到"无法找到id为1的可拖动元素"
在下面的代码中,UI呈现了两个"Column"组件,每个列包含两个名为"Tasks"的可拖动元素。当用户在列之间拖动"Task"时,代码可以正常工作 - 到某个程度为止。当用户持续拖动任务组件时,最终它们将停止拖动,并且用户会收到一个错误消息,上面写着:
无法找到id为X的可拖动项
我不知道为什么会发生这种情况,也不知道如何修复。
注意:我假设库的工作方式是当您拖动元素时,您需要在onDragEnd
函数中重新排序和更新状态。
以下是我的代码:
app.js
import React,{useState} from 'react'; import {DragDropContext} from 'react-beautiful-dnd'; import helper from './helper_functions' import Column from './Components/Column'; function App() { let initialState = [ { groupName:"今天", tasks:[ {id:"1", title:"测试-1"}, {id:"2", title:"测试-2"} ] }, { groupName:"明天", tasks:[ {id:"3", title:"测试-3"}, {id:"4", title:"测试-4"} ] }, ] const [taskList, setTasks] = useState(initialState) function onDragEnd(val){ let result = helper.reorder(val.source,val.destination,taskList); setTasks(result) } return (); } export default App; 上下文你好世界
src/helper_functions
export default { reorder:function(source,destination,taskDataArr){ let taskData = [...taskDataArr] // //_____________________________________________________________源数据 let sourceGroupIndex = taskData.findIndex((val, index) => { // 遍历并找到列表数据中“今天”(或其他)的索引 return val.groupName === source.droppableId }); let draggedTask = taskData[sourceGroupIndex].tasks.find((val, index) => { // 根据索引获取特定任务对象 return source.index === index }); // 拖动的对象 let sourceListCopyWithElementRemoved = taskData[sourceGroupIndex].tasks.filter((val, index) => { return index !== source.index // 从数组中删除拖动的元素 }); // //__________________________________________________________________目标数据 let destinationGroupIndex = taskData.findIndex((val, index) => { // 遍历并找到列表数据中“明天”(或其他)的索引 return val.groupName === destination.droppableId }); taskData[destinationGroupIndex].tasks.splice(destination.index, 0, draggedTask); // 将拖动的项目插入到新位置 taskData[sourceGroupIndex].tasks = sourceListCopyWithElementRemoved return taskData } }
src/Components/Column
import React from 'react'; import {Droppable} from 'react-beautiful-dnd'; import Task from "../../Components/Task" function Column(props){ const { classes, droppableId, list, type} = props; let style = { backgroundColor:"orange", height:"300px", width:"400px", margin:"100px" } console.log(list) return ({provided => ( ) } export default Column{droppableId}
{list.map((val,index)=>{ return})} {provided.placeholder} ) }
src/Components/Task
import React from 'react'; import {Draggable} from 'react-beautiful-dnd'; function Task(props){ const { classes, id, index,title } = props; let style = { backgroundColor:"red", } return ({(provided) => ( {title}
)} ) } export default Task