You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用dnd-kit拖拽排序时连续交换元素出现异常问题

问题分析与解决方案

你的dnd-kit排序异常问题由两个核心错误导致:

1. SortableContext的items参数类型错误

SortableContext要求items属性传入可排序元素id组成的数组,但你当前传入的是完整的creaturesTokens对象数组,这会导致dnd-kit无法正确识别元素的排序标识。

修改方案:
将SortableContext的items改为提取每个元素的token id:

<SortableContext
  items={creaturesTokens.map(token => token.data.id)}
  strategy={verticalListSortingStrategy}
>

2. onDragEnd中的索引逻辑与arrayMove参数顺序错误

  • 你混淆了creaturesTokens数组外层元素的id和内部tokenData的id,useSortable使用的是tokenData.id,所以查找索引时应该匹配token.data.id
  • arrayMove的参数顺序是arrayMove(数组, 原索引, 目标索引),你当前把原索引和目标索引搞反了,导致排序方向错误

修正后的onDragEnd函数:

function onDragEnd(event: DragEndEvent) {
  const { active, over } = event;
  if (!over || active.id === over.id) return;

  setCreaturesToken((tokens) => {
    const oldIndex = tokens.findIndex(token => token.data.id === active.id);
    const newIndex = tokens.findIndex(token => token.data.id === over.id);
    return arrayMove(tokens, oldIndex, newIndex);
  });
}

额外提示

FieldTokenComponent中使用了未定义的tokenEliminated变量,需要补充该变量的定义(比如从props传入或在组件内维护状态),避免运行时报错。


内容的提问来源于stack exchange,提问作者MordecaiOD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 15:35:10