From e42e60b1d96980bd507cc70f7f688cc43d66b962 Mon Sep 17 00:00:00 2001 From: KaiyiWing Date: Tue, 18 Apr 2023 17:24:09 +0800 Subject: [PATCH] feat: make dictID robust --- src/pages/Typing/index.tsx | 15 +++++++++++++-- src/store/index.ts | 7 ++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/pages/Typing/index.tsx b/src/pages/Typing/index.tsx index b7afa8e7..0ddccd8d 100644 --- a/src/pages/Typing/index.tsx +++ b/src/pages/Typing/index.tsx @@ -11,11 +11,12 @@ import Header from '@/components/Header' import Loading from '@/components/Loading' import StarCard from '@/components/StarCard' import Tooltip from '@/components/Tooltip' -import { currentChapterAtom, currentDictInfoAtom, isLoopSingleWordAtom, randomConfigAtom } from '@/store' +import { idDictionaryMap } from '@/resources/dictionary' +import { currentChapterAtom, currentDictIdAtom, currentDictInfoAtom, isLoopSingleWordAtom, randomConfigAtom } from '@/store' import { IsDesktop, isLegal } from '@/utils' import { useSaveChapterRecord } from '@/utils/db' import { useMixPanelChapterLogUploader } from '@/utils/mixpanel' -import { useAtomValue } from 'jotai' +import { useAtom, useAtomValue } from 'jotai' import React, { useCallback, useEffect, useState } from 'react' import { useHotkeys } from 'react-hotkeys-hook' import { NavLink } from 'react-router-dom' @@ -28,6 +29,7 @@ const App: React.FC = () => { const currentWord = typingState.chapterData.words[typingState.chapterData.index] const currentChapter = useAtomValue(currentChapterAtom) + const [currentDictId, setCurrentDictId] = useAtom(currentDictIdAtom) const currentDictInfo = useAtomValue(currentDictInfoAtom) const chapterLogUploader = useMixPanelChapterLogUploader(typingState) @@ -51,6 +53,15 @@ const App: React.FC = () => { }, 500) } }, []) + + // 在组件挂载和currentDictId改变时,检查当前字典是否存在,如果不存在,则将其重置为默认值 + useEffect(() => { + const id = currentDictId + if (!(id in idDictionaryMap)) { + setCurrentDictId('cet4') + } + }, [currentDictId, setCurrentDictId]) + useHotkeys( 'enter', () => { diff --git a/src/store/index.ts b/src/store/index.ts index eeb7c75f..7e62ed5e 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -8,7 +8,12 @@ import { atomWithStorage } from 'jotai/utils' export const currentDictIdAtom = atomWithStorage('currentDict', 'cet4') export const currentDictInfoAtom = atom((get) => { const id = get(currentDictIdAtom) - const dict = idDictionaryMap[id] + let dict = idDictionaryMap[id] + // 如果 dict 不存在,则返回 cet4. Typing 中会检查 DictId 是否存在,如果不存在则会重置为 cet4 + if (!dict) { + dict = idDictionaryMap.cet4 + } + const dictionary = { ...dict, chapterCount: Math.ceil(dict.length / CHAPTER_LENGTH) } return dictionary || null })