函数组件每重新渲染,内部定义的函数都会重新计算,从而导致防抖计时失效
1const getSuggest = debounce(() => {
2 request
3 .get("/search/suggest", {
4 params: { keywords: keywords.current, type: "mobile" },
5 })
6 .then((res: any) => {
7 if (res.code === 200 && res.result?.allMatch) {
8 setSuggestdata(res.result.allMatch);
9 } else {
10 setSuggestdata([]);
11 }
12 });
13 }, 500);
使用useCallback将防抖函数缓存住,避免被重新计算
1 const getSuggest = useCallback(
2 debounce(() => {
3 request
4 .get("/search/suggest", {
5 params: { keywords: keywords.current, type: "mobile" },
6 })
7 .then((res: any) => {
8 if (res.code === 200 && res.result?.allMatch) {
9 setSuggestdata(res.result.allMatch);
10 } else {
11 setSuggestdata([]);
12 }
13 });
14 }, 500),
15 []
16 );
17