前端实现搜索历史缓存

实现思路

将搜索历史缓存至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值

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值