From ef41833519f64b8a2e37c6a80f132f741f20551b Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Sat, 11 Feb 2023 19:41:21 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E8=A1=A8=E6=83=85=E9=9D=A2=E6=9D=BF?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=B8=AD=E8=8B=B1=E5=9B=BD=E9=99=85=E5=8C=96?= =?UTF-8?q?=EF=BC=8C=E5=B9=B6=E4=BC=98=E5=8C=96useStorage=E7=9A=84?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 以减少在使用hooks时因异步带来的gap --- client/shared/manager/storage.ts | 16 ++++++++++++++-- client/web/src/components/Emoji/Picker.tsx | 5 +++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/client/shared/manager/storage.ts b/client/shared/manager/storage.ts index 51314f1c..c2182d8a 100644 --- a/client/shared/manager/storage.ts +++ b/client/shared/manager/storage.ts @@ -17,6 +17,11 @@ export interface StorageObject { export const [getStorage, setStorage] = buildRegFn<() => StorageObject>('storage'); +/** + * 持久化hook的缓存, 减少因一步获取数据导致的gap + */ +const useStorageCache = new Map(); + /** * 管理持久化存储数据 * @param key 存储键 @@ -26,18 +31,24 @@ export function useStorage( key: string, defaultValue?: T ): [T | undefined, { set: (v: T) => void; save: (v: T) => void }] { - const [value, setValue] = useState(defaultValue); + const [value, setValue] = useState( + useStorageCache.get(key) ?? defaultValue + ); useLayoutEffect(() => { getStorage() .get(key) - .then((data: T) => setValue(data ?? defaultValue)); + .then((data: T) => { + setValue(data ?? defaultValue); + useStorageCache.set(key, data ?? defaultValue); + }); }, [key]); const set = useCallback( (newVal: T) => { setValue(newVal); getStorage().set(key, newVal); + useStorageCache.set(key, newVal); }, [key] ); @@ -46,6 +57,7 @@ export function useStorage( (newVal: T) => { setValue(newVal); getStorage().save(key, newVal); + useStorageCache.set(key, newVal); }, [key] ); diff --git a/client/web/src/components/Emoji/Picker.tsx b/client/web/src/components/Emoji/Picker.tsx index d46988dd..80f06bf4 100644 --- a/client/web/src/components/Emoji/Picker.tsx +++ b/client/web/src/components/Emoji/Picker.tsx @@ -3,7 +3,8 @@ import { isValidStr, useColorScheme, useLanguage } from 'tailchat-shared'; import { emojiData } from './const'; import Picker from '@emoji-mart/react'; import type { EmojiData } from './types'; -import i18n from '@emoji-mart/data/i18n/zh.json'; +import i18nZh from '@emoji-mart/data/i18n/zh.json'; +import i18nEn from '@emoji-mart/data/i18n/en.json'; import spritesUrl from './twitter.png'; import './Picker.less'; @@ -36,7 +37,7 @@ export const EmojiPicker: React.FC = React.memo((props) => { set="twitter" data={emojiData} theme={isDarkMode ? 'dark' : 'light'} - i18n={language === 'zh-CN' ? i18n : undefined} + i18n={language === 'zh-CN' ? i18nZh : i18nEn} previewPosition="none" skinTonePosition="none" onEmojiSelect={handleSelect}