You need to enable JavaScript to run this app. WordPress古腾堡块用react-sortable-hoc报已卸载组件找不到节点错误如何修复
优惠活动
大模型
产品
解决方案
定价
更多

WordPress古腾堡块用react-sortable-hoc报已卸载组件找不到节点错误如何修复

问题根因

  • 你将SortableItem、SortableList两个高阶组件的定义放在了edit函数内部,Gutenberg编辑器的edit函数会在每次属性更新时重新执行,每次执行都会生成全新的组件实例,触发React强制卸载旧组件、挂载新组件,就会出现第一个Unable to find node on an unmounted component报错。
  • react-sortable-hoc依赖内部ref持久化存储拖拽元素信息,组件频繁重建导致ref丢失,就触发第二个*undefined is not an object (evaluating 'this.refs[collection].indexOf')*报错。
  • 额外隐患:代码中使用了arrayMove方法但没有从react-sortable-hoc中导入,也会触发运行时报错。

修复方案

将高阶组件定义移到edit函数外部,补充缺失的arrayMove导入即可,修改后完整代码如下:

import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';

// 组件定义移到edit函数外部,全局仅初始化一次
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
const SortableList = SortableContainer(({items}) => {
    return (
        <ul>
            {items.map((value, index) => (
                <SortableItem
                    key={`item-${index}-${value}`} // 加入index避免item值重复时key冲突
                    index={index}
                    value={value}
                />
            ))}
        </ul>
    );
});

registerBlockType('ay/sortable', {
    title: __('Sortable'),        
    attributes: {
        items: {
            type: 'array',
            default: [
                'Item 1',
                'Item 2',
                'Item 3',                    
            ],
        },
    },

    edit(props) {
        const {
            attributes: {items},
            setAttributes,
        } = props;

        const onSortEnd = ({oldIndex, newIndex}) => {
            setAttributes(({items}) => ({
                items: arrayMove(items, oldIndex, newIndex),
            }));
        };

        return (
            <div>
                <SortableList items={items} onSortEnd={onSortEnd} />
            </div>
        );
    },

    save(props) {
        return null;
    },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 01:18:02