From 647034f3c04aca5d6753e4a7c3486a0cf67cb4f7 Mon Sep 17 00:00:00 2001 From: YuanShiJiLoong <2450829984@qq.com> Date: Tue, 24 Feb 2026 21:15:50 +0900 Subject: [PATCH] fix: auto-recover corrupted chapter data on startup --- app/components/Sidebar.js | 2 +- app/page.js | 16 ++++++++++++++-- app/store/useAppStore.js | 2 +- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/app/components/Sidebar.js b/app/components/Sidebar.js index 1d860e6..5ffdaf3 100644 --- a/app/components/Sidebar.js +++ b/app/components/Sidebar.js @@ -96,7 +96,7 @@ export default function Sidebar() { } }, [activeChapterId, chapters, showToast, t]); - const totalWords = chapters.reduce((sum, ch) => sum + (ch.wordCount || 0), 0); + const totalWords = Array.isArray(chapters) ? chapters.reduce((sum, ch) => sum + (ch.wordCount || 0), 0) : 0; return ( <> diff --git a/app/page.js b/app/page.js index 0719420..c20700d 100644 --- a/app/page.js +++ b/app/page.js @@ -68,7 +68,19 @@ export default function Home() { // 初始化数据 useEffect(() => { const initData = async () => { - const saved = await getChapters(); + let saved = await getChapters(); + // 自动修复:过滤掉损坏的章节数据(如缺少 id 或非对象的条目) + if (Array.isArray(saved)) { + const cleaned = saved.filter(ch => ch && typeof ch === 'object' && ch.id); + if (cleaned.length !== saved.length) { + console.warn(`[数据修复] 发现 ${saved.length - cleaned.length} 条损坏的章节数据,已自动清理`); + saved = cleaned; + const { saveChapters } = await import('./lib/storage'); + await saveChapters(saved); + } + } else { + saved = []; + } if (saved.length === 0) { const first = await createChapter(t('page.firstChapterTitle')); setChapters([first]); @@ -147,7 +159,7 @@ export default function Home() { }, []); // 当前活跃章节 - const activeChapter = chapters.find(ch => ch.id === activeChapterId); + const activeChapter = Array.isArray(chapters) ? chapters.find(ch => ch.id === activeChapterId) : null; const handleEditorUpdate = useCallback(async ({ html, wordCount }) => { if (!activeChapterId) return; diff --git a/app/store/useAppStore.js b/app/store/useAppStore.js index 681d70c..a1df7ed 100644 --- a/app/store/useAppStore.js +++ b/app/store/useAppStore.js @@ -4,7 +4,7 @@ export const useAppStore = create((set, get) => ({ // --- Chapter State --- chapters: [], activeChapterId: null, - setChapters: (chapters) => set({ chapters }), + setChapters: (chapters) => set({ chapters: Array.isArray(chapters) ? chapters.filter(ch => ch && typeof ch === 'object' && ch.id) : [] }), setActiveChapterId: (id) => set({ activeChapterId: id }), addChapter: (chapter) => set((state) => ({ chapters: [...state.chapters, chapter] })), deleteChapter: (id) => set((state) => ({ chapters: state.chapters.filter((ch) => ch.id !== id) })),