簡體   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