From b3b23c7e2d2bcd17d8692b43af1569b3d331983b Mon Sep 17 00:00:00 2001 From: d3george Date: Tue, 29 Oct 2024 18:45:25 +0800 Subject: [PATCH] refactor: SearchBar component refact --- src/layouts/_common/search-bar.tsx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/layouts/_common/search-bar.tsx b/src/layouts/_common/search-bar.tsx index 796c1265..f7ce3976 100644 --- a/src/layouts/_common/search-bar.tsx +++ b/src/layouts/_common/search-bar.tsx @@ -2,7 +2,7 @@ import { Empty, GlobalToken, Input, InputRef, Modal } from 'antd'; import match from 'autosuggest-highlight/match'; import parse from 'autosuggest-highlight/parse'; import Color from 'color'; -import { CSSProperties, useEffect, useRef, useState } from 'react'; +import { CSSProperties, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useBoolean, useEvent, useKeyPressEvent } from 'react-use'; import styled from 'styled-components'; @@ -30,19 +30,21 @@ export default function SearchBar() { }; const [searchQuery, setSearchQuery] = useState(''); - const [searchResult, setSearchResult] = useState(flattenedRoutes); const [selectedItemIndex, setSelectedItemIndex] = useState(0); - useEffect(() => { - const result = flattenedRoutes.filter( + const searchResult = useMemo(() => { + return flattenedRoutes.filter( (item) => - t(item.label).toLowerCase().indexOf(searchQuery.toLowerCase()) !== -1 || - item.key.toLowerCase().indexOf(searchQuery.toLowerCase()) !== -1, + t(item.label).toLowerCase().includes(searchQuery.toLowerCase()) || + item.key.toLowerCase().includes(searchQuery.toLowerCase()), ); - setSearchResult(result); - setSelectedItemIndex(0); }, [searchQuery, t, flattenedRoutes]); + // 在搜索结果变化时重置选中索引 + useEffect(() => { + setSelectedItemIndex(0); + }, [searchResult.length]); + const handleMetaK = (event: KeyboardEvent) => { if (event.metaKey && event.key === 'k') { // https://developer.mozilla.org/zh-CN/docs/Web/API/KeyboardEvent/metaKey