前端实现搜索历史缓存

122 阅读1分钟

实现方式

ahooks.js.org/zh-CN/hooks…

useLocalStorageState 可以将状态存储在 localStorage 中

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值