refactor(Company): 提取共享的 useStockSearch Hook
- 新增 useStockSearch.ts:统一股票模糊搜索逻辑 - 支持按代码或名称搜索 - 支持排除指定股票(用于对比场景) - 使用 useMemo 优化性能 - 重构 SearchBar.js:使用共享 Hook,减少 15 行代码 - 重构 CompareStockInput.tsx:使用共享 Hook,减少 20 行代码 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
59
src/views/Company/hooks/useStockSearch.ts
Normal file
59
src/views/Company/hooks/useStockSearch.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* useStockSearch - 股票模糊搜索 Hook
|
||||
*
|
||||
* 提取自 SearchBar.js 和 CompareStockInput.tsx 的共享搜索逻辑
|
||||
* 支持按代码或名称搜索,可选排除指定股票
|
||||
*/
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export interface Stock {
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface UseStockSearchOptions {
|
||||
excludeCode?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 股票模糊搜索 Hook
|
||||
*
|
||||
* @param allStocks - 全部股票列表
|
||||
* @param searchTerm - 搜索关键词
|
||||
* @param options - 可选配置
|
||||
* @param options.excludeCode - 排除的股票代码(用于对比场景)
|
||||
* @param options.limit - 返回结果数量限制,默认 10
|
||||
* @returns 过滤后的股票列表
|
||||
*/
|
||||
export const useStockSearch = (
|
||||
allStocks: Stock[],
|
||||
searchTerm: string,
|
||||
options: UseStockSearchOptions = {}
|
||||
): Stock[] => {
|
||||
const { excludeCode, limit = 10 } = options;
|
||||
|
||||
return useMemo(() => {
|
||||
const trimmed = searchTerm?.trim();
|
||||
if (!trimmed) return [];
|
||||
|
||||
const term = trimmed.toLowerCase();
|
||||
|
||||
return allStocks
|
||||
.filter((stock) => {
|
||||
// 排除指定股票
|
||||
if (excludeCode && stock.code === excludeCode) {
|
||||
return false;
|
||||
}
|
||||
// 按代码或名称匹配
|
||||
return (
|
||||
stock.code.toLowerCase().includes(term) ||
|
||||
stock.name.includes(trimmed)
|
||||
);
|
||||
})
|
||||
.slice(0, limit);
|
||||
}, [allStocks, searchTerm, excludeCode, limit]);
|
||||
};
|
||||
|
||||
export default useStockSearch;
|
||||
Reference in New Issue
Block a user