react-beautiful-dnd移除节点报错求助:非子节点无法执行removeChild
临时修复Gatsby + react-beautiful-dnd路由切换时的removeChild错误
在Gatsby项目里使用react-beautiful-dnd,每次离开对应页面都会抛出以下错误:
Error in function remove in ./node_modules/react-beautiful-dnd/dist/react-beautiful-dnd.esm.js:5017
Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
根源是Gatsby的路由卸载逻辑和react-beautiful-dnd的DOM节点清理逻辑冲突,这里给几个临时修复方案:
手动在组件卸载前清理DOM节点
利用React的useEffect清理函数,在组件卸载前检查并移除react-beautiful-dnd挂载到head的节点:import { useEffect, useRef } from 'react'; import { DragDropContext } from 'react-beautiful-dnd'; const YourDraggableComponent = () => { const dndContextRef = useRef(null); useEffect(() => { return () => { if (dndContextRef.current) { const head = document.head; const dndNode = dndContextRef.current; if (head.contains(dndNode)) { head.removeChild(dndNode); } } }; }, []); return ( <DragDropContext ref={dndContextRef} {/* 你的其他配置props */}> {/* 你的拖拽列表/组件内容 */} </DragDropContext> ); };给react-beautiful-dnd打补丁(持久化修改)
找到node_modules/react-beautiful-dnd/dist/react-beautiful-dnd.esm.js里报错的remove函数,在执行removeChild前先判断节点是否属于head的子节点:// 替换原5017行代码 const head = getHead(); if (head.contains(current)) { head.removeChild(current); }然后用patch-package把这个修改做成持久化补丁:
- 安装依赖:
npm install patch-package --save-dev - 运行命令生成补丁:
npx patch-package react-beautiful-dnd - 把项目根目录生成的
patches文件夹提交到版本控制,后续安装依赖会自动应用补丁
- 安装依赖:
用Suspense延迟组件卸载
在拖拽页面的路由外层包裹Suspense,给react-beautiful-dnd足够时间完成DOM清理:import { Suspense } from 'react'; import { Route } from '@gatsbyjs/reach-router'; import DraggablePage from './DraggablePage'; const AppRoutes = () => ( <Route path="/your-draggable-page" element={ <Suspense fallback={<div>加载中...</div>}> <DraggablePage /> </Suspense> } /> );
内容的提问来源于stack exchange,提问作者fullStackChris
相关产品推荐
相关产品推荐

