【发布时间】:2021-10-26 12:02:48
【问题描述】:
我一直在玩 react-beautiful-dnd 和 hooks(对 react 来说非常新)——由于某种原因,我的状态不会在拖动时更新。 (编辑:我知道该逻辑仅适用于“相同类别”拖动 - 这对我来说也不更新 UI)
数据(简化)
const skills = {
skills: {
skill1: {
id: "skill1",
name: "Communication"
},
skill2: {
id: "skill2",
name: "Empathy"
},
skill3: {
id: "skill3",
name: "Initiative"
}
},
categories: {
cat1: {
id: "cat1",
name: "Core",
skillIds: ["skill1", "skill2", "skill3", "skill4"]
},
cat2: {
id: "cat2",
name: "Craft",
skillIds: ["skill5", "skill6", "skill7", "skill8"]
},
cat3: {
id: "cat3",
name: "Leadership",
skillIds: ["skill9", "skill10"]
}
},
categoryOrder: ["cat1", "cat2", "cat3"]
};
更新skillIds数组到正确类别的函数
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const onDragEnd = (result) => {
const { source, destination } = result;
// dropped outside the list
if (!destination) {
return;
}
// Handle moving within one category
if (source.droppableId === destination.droppableId) {
const catSkills = data.categories[source.droppableId].skillIds;
const items = reorder(catSkills, source.index, destination.index);
const newData = {
...data,
categories: {
...data.categories,
[source.droppableId]: {
...data.categories[source.droppableId],
skillIds: items
}
}
};
setData(newData);
}
};
我创建了一个简化的代码框来测试 - https://codesandbox.io/s/hooks-problem-il5m4
任何帮助表示赞赏!
【问题讨论】:
标签: reactjs setstate react-beautiful-dnd