react hook配合lodash实现防抖搜索
例子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]);
下一篇:js简单使用定时任务