refactor(admin): LiteMermaid 用 usehooks-ts useIsMounted 替代手写 cancelled 标志

This commit is contained in:
2026-08-08 17:27:14 +08:00
parent d324b2fb0a
commit 8ddc3ea690

View File

@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { useIsMounted } from 'usehooks-ts';
interface LiteMermaidProps {
children: string;
@@ -11,9 +12,9 @@ interface LiteMermaidProps {
export function LiteMermaid({ children }: LiteMermaidProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [error, setError] = useState<string | null>(null);
const isMounted = useIsMounted();
useEffect(() => {
let cancelled = false;
const container = containerRef.current;
if (!container) return;
@@ -22,21 +23,17 @@ export function LiteMermaid({ children }: LiteMermaidProps) {
const mermaid = (await import('mermaid')).default;
mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'strict' });
const { svg } = await mermaid.render(`mermaid-${crypto.randomUUID()}`, children);
if (!cancelled) {
if (isMounted()) {
const doc = new DOMParser().parseFromString(svg, 'image/svg+xml');
container.replaceChildren(doc.documentElement);
setError(null);
}
} catch (e) {
if (!cancelled) {
if (isMounted()) {
setError(e instanceof Error ? e.message : '图表渲染失败');
}
}
})();
return () => {
cancelled = true;
};
}, [children]);
if (error) {