From 371d4ce32790beff1277e96d428a0c1fd4fe2328 Mon Sep 17 00:00:00 2001 From: ssdfasd <2156608475@qq.com> Date: Fri, 13 Mar 2026 18:38:38 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20markdown=20?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E4=BF=9D=E5=AD=98=E5=90=8E=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E4=B8=A2=E5=A4=B1=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 saveContent 中缓存 unsavedContent,避免 async 期间的竞态条件 - 在 useMarkdownLogic 中添加 lastContentRef 跟踪内容变化,防止不必要的编辑器更新 --- src/hooks/domain/useMarkdownLogic.ts | 13 ++++++++++--- src/stores/tabStore.ts | 7 +++++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/hooks/domain/useMarkdownLogic.ts b/src/hooks/domain/useMarkdownLogic.ts index 2b54a96..18cb2f3 100644 --- a/src/hooks/domain/useMarkdownLogic.ts +++ b/src/hooks/domain/useMarkdownLogic.ts @@ -85,6 +85,8 @@ export const useMarkdownLogic = ({ const readOnlyRef = useRef(readOnly) const ctxRef = useRef(null) + const lastContentRef = useRef('') + useEffect(() => { onChangeRef.current = onChange }, []) @@ -117,23 +119,28 @@ export const useMarkdownLogic = ({ } }, [readOnly]) - // 在只读模式下动态更新内容 + // 在只读模式下动态更新内容(仅当 content 真正变化时) useEffect(() => { if (!ctxRef.current || !readOnly) return + + // 只有当 content 真正变化时才更新编辑器 + if (content === lastContentRef.current) return + lastContentRef.current = content + try { const view = ctxRef.current.get(editorViewCtx) const parser = ctxRef.current.get(parserCtx) const doc = parser(content) if (!doc) return - const state = view.state - view.dispatch(state.tr.replaceWith(0, state.doc.content.size, doc)) + view.dispatch(view.state.tr.replaceWith(0, view.state.doc.content.size, doc)) } catch { // 编辑器可能尚未就绪 } }, [content, readOnly]) return useEditor((root) => { + lastContentRef.current = content return Editor.make() .config((ctx) => { ctxRef.current = ctx diff --git a/src/stores/tabStore.ts b/src/stores/tabStore.ts index fada79f..2ac5218 100644 --- a/src/stores/tabStore.ts +++ b/src/stores/tabStore.ts @@ -331,7 +331,9 @@ export const useTabStore = create((set, get) => { const isAsyncImportProcessing = isAsyncImportProcessingContent(tab.content) if (isAsyncImportProcessing) return - await saveFileContent(filePath, tab.unsavedContent) + const contentToSave = tab.unsavedContent + + await saveFileContent(filePath, contentToSave) set((state) => { const newTabs = new Map(state.tabs) @@ -339,7 +341,8 @@ export const useTabStore = create((set, get) => { if (currentTab) { newTabs.set(filePath, { ...currentTab, - content: currentTab.unsavedContent, + content: contentToSave, + unsavedContent: contentToSave, isEditing: false, }) }