You need to enable JavaScript to run this app. React使用react-beautiful-dnd的DragDropContext时出现useState相关错误求助
优惠活动
大模型
产品
解决方案
定价
更多

React使用react-beautiful-dnd的DragDropContext时出现useState相关错误求助

修复react-beautiful-dnd的TypeError: null is not an object (evaluating 'dispatcher.useState')错误

问题描述

尝试使用react-beautiful-dnd实现水平拖拽列表,已完成列表项定义、状态声明、DragDropContext及onDragComplete函数的实现,但运行时出现TypeError: null is not an object (evaluating 'dispatcher.useState')错误。

原代码

import { usePreloadedQuery } from 'react-relay/hooks';
import graphql from 'babel-plugin-relay/macro';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import { useState } from 'react';


export const listItems = [ 
  { id: '1', label: 'assignedTasks' },
  { id: '2', label: 'manualProgress' },
  { id: '3', label: 'news' },
  { id: '4', label: 'notifications' },
  { id: '5', label: 'documentFavorites' },
   ];

const query = graphql`
  query DashboardSettingsQuery {
    currentMember {
      organisation {
        dashboardSettings
      }
    }
  }
`;

export default function DashboardSettings(props) {
  console.log(props);
  const data = usePreloadedQuery(query, props.prepared.dashboardSettingsQuery);
  const [dragDropList, setDragDropList] = useState(listItems);  
  console.log(data);

  const onDragComplete = (result) => {
    if (!result.destination) return;
  
    const arr = [...dragDropList];
  
    //Changing the position of Array element
    let removedItem = arr.splice(result.source.index, 1)[0];
    arr.splice(result.destination.index, 0, removedItem);
  
    //Updating the list
    setDragDropList(arr);
  };

  return(
    <>
    <h1>dashboardSettings</h1>
    <div className="container">
  <div className="card">
    <div className="header">Horizontal Drag and Drop List</div>

    <DragDropContext onDragEnd={onDragComplete}>
      <Droppable droppableId="drag-drop-list" direction="horizontal">
        {(provided, snapshot) => (
          <div
            className="drag-drop-list-container"
            {...provided.droppableProps}
            ref={provided.innerRef}
          >
            {dragDropList.map((item, index) => (
              <Draggable key={item.id} draggableId={item.label} index={index}>
                {(provided) => (
                  <div
                    className="item-card"
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                  >
                    <span className="material-symbols-outlined">
                      drag_indicator
                    </span>
                    <div className="char-avatar">{item.label.charAt(0)}</div>
                    <p className="label">{item.label}</p>
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  </div>
</div>;
</>
  );
}

错误信息

[Error] TypeError: null is not an object (evaluating 'dispatcher.useState')
useState (vendors-node_modules_react-beautiful-dnd_dist_react-beautiful-dnd_esm_js.chunk.js:43660)
useMemoOne (vendors-node_modules_react-beautiful-dnd_dist_react-beautiful-dnd_esm_js.chunk.js:46187)
DragDropContext (vendors-node_modules_react-beautiful-dnd_dist_react-beautiful-dnd_esm_js.chunk.js:8849)
renderWithHooks (bundle.js:67613)
mountIndeterminateComponent (bundle.js:71278)
callCallback (bundle.js:55409)
dispatchEvent
invokeGuardedCallbackDev (bundle.js:55458)
invokeGuardedCallback (bundle.js:55520)
beginWork$1 (bundle.js:78533)
performUnitOfWork (bundle.js:77666)
workLoopSync (bundle.js:77579)
renderRootSync (bundle.js:77548)
recoverFromConcurrentError (bundle.js:76956)
performConcurrentWorkOnRoot (bundle.js:76857)
performConcurrentWorkOnRoot
workLoop (bundle.js:126091)
flushWork (bundle.js:126065)
performWorkUntilDeadline (bundle.js:126349)

修复方案

1. 升级react-beautiful-dnd版本

该错误大概率是因为react-beautiful-dnd与当前React版本不兼容导致的,react-beautiful-dnd需要匹配React 16.x-18.x的版本,且React 18需要使用>=13.1.1的react-beautiful-dnd版本。执行以下命令升级:

npm install react-beautiful-dnd@latest
# 或使用yarn
yarn add react-beautiful-dnd@latest

2. 拆分组件避免上下文冲突

将拖拽列表逻辑从Relay查询组件中拆分出来,封装为独立子组件,避免Relay的usePreloadedQuery与react-beautiful-dnd的钩子函数在同一组件层级引发上下文冲突。

拆分后的拖拽列表子组件(DragDropList.js)

import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import { useState } from 'react';

export const listItems = [ 
  { id: '1', label: 'assignedTasks' },
  { id: '2', label: 'manualProgress' },
  { id: '3', label: 'news' },
  { id: '4', label: 'notifications' },
  { id: '5', label: 'documentFavorites' },
];

export default function DragDropList() {
  const [dragDropList, setDragDropList] = useState(listItems);  

  const onDragComplete = (result) => {
    if (!result.destination) return;
  
    const arr = [...dragDropList];
    let removedItem = arr.splice(result.source.index, 1)[0];
    arr.splice(result.destination.index, 0, removedItem);
    setDragDropList(arr);
  };

  return (
    <DragDropContext onDragEnd={onDragComplete}>
      <Droppable droppableId="drag-drop-list" direction="horizontal">
        {(provided, snapshot) => (
          <div
            className="drag-drop-list-container"
            {...provided.droppableProps}
            ref={provided.innerRef}
          >
            {dragDropList.map((item, index) => (
              <Draggable key={item.id} draggableId={item.label} index={index}>
                {(provided) => (
                  <div
                    className="item-card"
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                  >
                    <span className="material-symbols-outlined">
                      drag_indicator
                    </span>
                    <div className="char-avatar">{item.label.charAt(0)}</div>
                    <p className="label">{item.label}</p>
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
}

修改后的DashboardSettings组件

import { usePreloadedQuery } from 'react-relay/hooks';
import graphql from 'babel-plugin-relay/macro';
import DragDropList from './DragDropList';

const query = graphql`
  query DashboardSettingsQuery {
    currentMember {
      organisation {
        dashboardSettings
      }
    }
  }
`;

export default function DashboardSettings(props) {
  console.log(props);
  const data = usePreloadedQuery(query, props.prepared.dashboardSettingsQuery);
  console.log(data);

  return(
    <>
      <h1>dashboardSettings</h1>
      <div className="container">
        <div className="card">
          <div className="header">Horizontal Drag and Drop List</div>
          <DragDropList />
        </div>
      </div>
    </>
  );
}

内容的提问来源于stack exchange,提问作者R-me

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:44:51