【问题标题】:Lodash throttle not throttling?Lodash油门不节流?
【发布时间】:2022-08-11 19:25:19
【问题描述】:

我第一次尝试应用 lodash 油门。

我知道必须在 useCallback 内应用油门,否则每次重新渲染都会调用它(在我的情况下,每次用户搜索的新按键都将调用它)。

我拥有的代码是有效的,并且逻辑似乎很有意义 - 但是没有应用油门,因此每次击键都会进行 api 调用。

关于我的逻辑在哪里失败的任何指示?

import {
    useEffect,
    useCallback
} from \'react\';
import { throttle } from \'lodash\';
import { getAllUsers } from \'../../../api/api\';
import { USER_ROLE } from \'../../../types/types\'

interface IProps extends Omit<unknown, \'children\'> {
    search?: string;
}

const DemoFanManagementTable = ({ search }: IProps): JSX.Element => {

    const getFans = (search?: string) => {
        console.log(\"getFans ran\")
        const fans = getAllUsers({ search }, USER_ROLE.FAN);
        //logs a promise
        console.log(\"logging fans \", fans)
        return fans;
    }

    //throttledSearch is running every time search changes
    const throttledSearch = useCallback((search?: string) => {
        console.log(\"throttledSearch ran\")
        return throttle(
            //throttle is not throttling, functions run every keystroke
            () => {
                getFans(search), 10000, { leading: true, trailing: true }
            }
        )
    }, [search])

    //useEffect is running every time search changes
    useEffect(() => {
        return throttledSearch(search)
    }, [search]);

    return (
        <div>
            {search}
        </div>
    );
};

export default DemoFanManagementTable;

    标签: javascript reactjs typescript lodash throttling


    【解决方案1】:

    这里有一些问题,首先您将整个 throttle func 包装在一个匿名函数中,而不仅仅是第一个参数:

    throttle(
      (search: string) => getFans(search),
      1000,
      { leading: true, trailing: true }
    )
    

    第二个useCallback 不适合,因为每次调用它时,它都会返回一个新的限制函数。

    第三,您已将[search] 作为useCallback 的依赖项传递,因此即使它按您预期的方式工作,每次search 更改时它都会失效并且无论如何都不起作用。

    更好的选择是useMemo,因为它在渲染中保持相同的节流功能。

    const throttledSearch = useMemo(
      () =>
        throttle(
          (search: string) => getFans(search),
          10000,
          { leading: true, trailing: true }
        ),
      []
    );
    
    useEffect(() => {
      return throttledSearch(search);
    }, [search]);
    

    由于 getFans 采用相同的搜索参数,您可以将其缩短为:

    const throttledSearch = useMemo(() =>
      throttle(getFans, 10000, { leading: true, trailing: true }),
    []);
    

    【讨论】:

    • 你怎么是return throttledSearch() 而不仅仅是throttledSearch
    猜你喜欢
    • 2020-12-05
    • 2021-07-15
    • 1970-01-01
    • 2021-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    相关资源
    最近更新 更多