Skip to content

Commit 8c459a0

Browse files
committed
fix: 修复Markdown编辑器数据恢复问题,确保正确显示从localStorage恢复的文本
1 parent fd83bc5 commit 8c459a0

File tree

1 file changed

+48
-4
lines changed

1 file changed

+48
-4
lines changed

src/components/ChallengeContributePage/components/DescriptionFields.tsx

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,30 @@ const DescriptionFields: React.FC<SectionProps> = ({ form }) => {
8888
render: (text: string) => text
8989
});
9090
const styleRef = useRef<HTMLStyleElement | null>(null);
91+
const isInitializedRef = useRef<boolean>(false);
92+
93+
// 安全地将表单值转换为字符串
94+
const ensureString = (value: any): string => {
95+
if (value === null || value === undefined) {
96+
return '';
97+
}
98+
if (typeof value === 'string') {
99+
return value;
100+
}
101+
if (typeof value === 'object') {
102+
try {
103+
// 尝试从对象中提取text属性或转换为JSON字符串
104+
if (value.text && typeof value.text === 'string') {
105+
return value.text;
106+
}
107+
return JSON.stringify(value);
108+
} catch (e) {
109+
console.error('无法将对象转换为字符串', e);
110+
return '';
111+
}
112+
}
113+
return String(value);
114+
};
91115

92116
// 处理图片上传
93117
const handleImageUpload = (file: File): Promise<string> => {
@@ -170,11 +194,31 @@ const DescriptionFields: React.FC<SectionProps> = ({ form }) => {
170194
}
171195
`;
172196

197+
// 同步初始值到state
173198
useEffect(() => {
174-
// 设置初始值
175-
setChineseMarkdown(form.getFieldValue('descriptionMarkdown') || '');
176-
setEnglishMarkdown(form.getFieldValue('descriptionMarkdownEn') || '');
199+
if (isInitializedRef.current) return;
200+
201+
// 获取表单中的值并确保是字符串类型
202+
const chnDesc = ensureString(form.getFieldValue('descriptionMarkdown'));
203+
const engDesc = ensureString(form.getFieldValue('descriptionMarkdownEn'));
204+
205+
// 设置到state中
206+
setChineseMarkdown(chnDesc);
207+
setEnglishMarkdown(engDesc);
177208

209+
// 如果恢复的值不是字符串类型,纠正表单中的值
210+
if (typeof form.getFieldValue('descriptionMarkdown') !== 'string') {
211+
form.setFieldsValue({ descriptionMarkdown: chnDesc });
212+
}
213+
214+
if (typeof form.getFieldValue('descriptionMarkdownEn') !== 'string') {
215+
form.setFieldsValue({ descriptionMarkdownEn: engDesc });
216+
}
217+
218+
isInitializedRef.current = true;
219+
}, [form]);
220+
221+
useEffect(() => {
178222
// 动态加载markdown-it库
179223
const script = document.createElement('script');
180224
script.src = 'https://cdn.jsdelivr.net/npm/markdown-it@12.0.4/dist/markdown-it.min.js';
@@ -206,7 +250,7 @@ const DescriptionFields: React.FC<SectionProps> = ({ form }) => {
206250
document.head.removeChild(script);
207251
}
208252
};
209-
}, [form]);
253+
}, []);
210254

211255
return (
212256
<>

0 commit comments

Comments
 (0)