实现思路
将搜索历史缓存至localStorage中,以USER_ACCOUNT作为用户区分
将状态存储在 localStorage 中的 Hook
具体实现
import { USER_ACCOUNT } from '@/utils/constant';
import { useLocalStorageState } from 'ahooks';
export default function useSearchHistory(maxNumber = 10): [string | undefined, (value: string) => void] {
const [historySearch, setHistorySearch] = useLocalStorageState<string | undefined>('historyItems');
const setHistoryItems = (value: string) => {
const keyword = value?.trim();
if (keyword) {
const account = localStorage.getItem(USER_ACCOUNT) as string;
// localStorage为null或该登录用户无搜索历史,直接设置
if (!historySearch || !historySearch[account]) {
const historyItems = JSON.parse(JSON.stringify(historySearch || {}));
historyItems[account] = keyword;
// useLocalStorageState会自动序列化和反序列化
setHistorySearch(historyItems);
} else {
const historyItems = JSON.parse(JSON.stringify(historySearch || {}));
let newItems = JSON.parse(JSON.stringify(historyItems[account])).split('|');
const isExists = newItems.filter((ele) => ele === keyword).length > 0;
// 判断关键字是否存在,存在就移除添加在首位
if (isExists) {
// 只有一个关键字则不用改变
if (newItems.length > 1) {
newItems = `${keyword}|${newItems.filter((e) => e !== keyword).join('|')}`;
} else {
newItems = keyword;
}
// 判断长度是否已经大于maxNumber个
} else if (newItems.length >= maxNumber) {
newItems.pop();
newItems = `${keyword}|${newItems.join('|')}`;
} else {
newItems = `${keyword}|${newItems.join('|')}`;
}
historyItems[account] = newItems;
setHistorySearch(historyItems);
}
}
};
return [historySearch, setHistoryItems];
}
使用方式
const [historySearch, setHistoryItems] = useSearchHistory();
historySearch用于页面渲染用户的历史搜索
setHistoryItems在input框onChang时传入value值