繁体   English   中英

如何在 React 中使用 lodash 限制这个 api 请求

[英]How to throttle this api request using lodash in React

我正在使用 React 并试图弄清楚如何实现 lodash debounce 方法来限制 api 请求。 我试图根据互联网上的示例来实现它,但在这种情况下似乎不起作用。 它应该等待大约 3 秒,然后再根据amountValue调用 api 方法,这基本上是一个 state 值。 这是我试图限制 api 请求的代码。

import debounce from 'lodash/debounce';

const [amountValue, setAmountValue] = useState('');

  const handleGetSwapPrice = useCallback(() => {
    getFinalPrice(amountValue)
      .then((res) => {
        const formattedPrice = formatCurrency('USD', res.price);
        if (!res.price) {
          setIsLoading(true);
        } else {
          setIsLoading(false);
        }
        setSwapPrice(formattedPrice);
      });
  }, [baseAsset, quoteAsset, transactionType]);


  useEffect(() => {
      handleGetSwapPrice();
    }
  }, []);

如果您使用 lodash 进行去抖动,则必须使用 useCallback 挂钩创建 function 的去抖动版本。 如果您在 Input 字段中使用它,请在 handleChange 中提供去抖 function。

import debounce from 'lodash/debounce';

const [amountValue, setAmountValue] = useState('');

  const handleGetSwapPrice = () => {
    getFinalPrice(amountValue)
      .then((res) => {
        const formattedPrice = formatCurrency('USD', res.price);
        if (!res.price) {
          setIsLoading(true);
        } else {
          setIsLoading(false);
        }
        setSwapPrice(formattedPrice);
      });
  }

  const debouncedAPICall = useCallback(debounce((e) => handleGetSwapPrice(e), 3000), []);

  useEffect(() => {
      debouncedAPICall();
    }
  }, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM