feat: make dictID robust

This commit is contained in:
KaiyiWing
2023-04-18 17:24:09 +08:00
parent 0b6eb085b7
commit e42e60b1d9
2 changed files with 19 additions and 3 deletions

View File

@@ -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',
() => {

View File

@@ -8,7 +8,12 @@ import { atomWithStorage } from 'jotai/utils'
export const currentDictIdAtom = atomWithStorage('currentDict', 'cet4')
export const currentDictInfoAtom = atom<Dictionary>((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
})