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