能否将CodeMirror6 EditorView存入React状态?组件销毁实例未定义问题
问题分析与解决方案
为什么清理时activeEditorView是undefined
你的useEffect依赖数组是空的,这意味着effect只会在组件挂载时执行一次。清理函数(return的函数)捕获的是effect执行时的activeEditorView值——也就是初始的undefined。虽然之后你调用了setActiveEditorView(view)更新了状态,但因为effect没有重新运行,清理函数里的activeEditorView始终是最初的undefined,自然无法调用destroy()。
正确的处理方式:用Ref存储EditorView实例
把activeEditorView从useState换成useRef,因为ref的.current属性是可变的,清理函数能访问到最新的实例:
import React, { useRef, useEffect } from 'react'; import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; const App: React.FC = () => { const edContainer = useRef<any>(); const activeEditorView = useRef<EditorView>(); // 改用useRef useEffect(() => { const state = EditorState.create({ doc: "hello", extensions: [] }); const view = new EditorView({ state, parent: edContainer.current, }); activeEditorView.current = view; // 存入ref的current return () => { if (activeEditorView.current) { activeEditorView.current.destroy(); } }; }, []); return ( <div> <div ref={edContainer}></div> </div> ); } export default App;
能不能把EditorView存入React状态?
不建议这么做。React状态设计用于存储可序列化、能触发重渲染的状态值(比如字符串、数字、普通对象等),而EditorView是包含DOM节点、内部状态的复杂类实例:
- 存入状态会导致React尝试对其进行比较,可能引发不必要的重渲染;
- 类实例的引用变化可能导致组件状态管理混乱,难以追踪;
- 像你遇到的这样,状态更新后无法在闭包中及时获取最新值,容易出现逻辑错误。
内容的提问来源于stack exchange,提问作者Dolphin
相关产品推荐
相关产品推荐

