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

如何在React useEffect钩子中执行原生JS类及处理代码拆分

解决方案

1. 无需转换为ES6类

旧的构造函数式JS类完全可以在React组件中直接使用,包括在useEffect钩子内实例化。ES6类只是构造函数的语法糖,底层逻辑和旧写法一致,React对两种写法都兼容,没必要额外转换。

2. 正确导入与实例化步骤

步骤1:完善原生JS文件的导出

你的editor.js目前是全局变量声明,在模块化的React项目中需要添加导出语句,确保能被组件正确导入:

// editor.js
EditorUi = function (editor, container, lightbox) {
  this.destroyFunctions = [];
  this.editor = editor || new Editor();
  this.container = container || document.body;
};

EditorUi.compactUi = true;
EditorUi.prototype.splitSize = 8;

// 添加导出语句
export default EditorUi;
// 若Editor类在其他独立文件,也需同步导出并在组件中导入
// export { Editor };

步骤2:在React组件中实例化与清理

在useEffect中实例化EditorUi,利用ref获取目标DOM容器,同时必须在组件卸载时执行清理逻辑,避免内存泄漏:

import React from 'react';
import EditorUi from '~/config/functions/bpm/EditorUi';
// 若Editor类在其他文件,需导入
// import { Editor } from '~/config/functions/bpm/Editor';

export default function MyComp() {
  const divGraph = React.useRef(null);
  const editorUiRef = React.useRef(null); // 保存实例,用于清理

  React.useEffect(() => {
    if (!divGraph.current) return;

    // 实例化EditorUi,传入ref指向的DOM容器
    editorUiRef.current = new EditorUi(null, divGraph.current);

    // 组件卸载时执行清理
    return () => {
      if (editorUiRef.current?.destroyFunctions) {
        editorUiRef.current.destroyFunctions.forEach(fn => fn());
      }
    };
  }, []); // 空依赖数组确保仅在组件挂载时执行一次

  return <div style={{ width: '100%', height: '80vh' }} ref={divGraph} />;
}

3. 关键注意事项

  • 确保Editor类可访问:如果Editor是独立文件,必须同步导入,否则new Editor()会抛出未定义错误。
  • 务必添加清理逻辑:原生JS库通常会绑定事件或操作DOM,组件卸载时执行销毁函数能避免内存泄漏。
  • 控制实例化时机:空依赖数组的useEffect确保实例仅创建一次,若需随依赖更新重新创建,可添加对应依赖项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:24:24