react hook配合lodash实现防抖搜索

2023-09-23 晚上前端 42 次浏览暂无评论

例子1:

const [key, setKey] = useState("");
const [t, setT] = useState(0);

const emptySearch = useMemo(() => {
  return !(t || key || startTime || endTime || qryUserId);
}, [t, key, startTime, endTime, qryUserId]);

useQuery({
  queryKey: [startTime, endTime, msgType, qryUserId, t],
  queryFn: () =>
    emptySearch
      ? []
      : getHistoryMessages({
          chat_id: curChatId,
          key,
          start_time: startTime,
          end_time: endTime,
          msg_type: msgType,
          qry_user_id: qryUserId,
        }),
  onSuccess: (res) => {
    setMsgData(res);
  },
});

const debouncedSearch = useCallback(
  _.debounce((value: string) => {
    value.trim() ? setT(new Date().getTime()) : setT(0);
  }, 500),
  []
);

<Input
  allowClear
  size="small"
  placeholder="搜索"
  prefix={<SearchOutlined />}
  className="rounded-md text-sm"
  value={key}
  onChange={(e) => {
    setKey(e.target.value);
    debouncedSearch(e.target.value);
  }}
/>

例子2:

  const debouncedInitChatSolveList = useCallback(
    _.debounce((params) => {
      initChatSolveList(params);
    }, 500),
    []
  );

  // 如果过滤条件发生变化,且当前列表为已完成,则重新拉取列表
  useEffect(() => {
    if (chatListStatus === CHAT_STATUS.SOLVED) {
      setChatListLoading(true);
      debouncedInitChatSolveList({
        status: CHAT_STATUS.SOLVED,
        key: curChatWhere.text,
        mine: curChatWhere.mine,
        page_index: curChatWhere.page_index,
      });
      setChatListLoading(false);
    }
  }, [curChatWhere]);

目录

ICP备案号:鲁ICP备2020040322号