简体   繁体   English

在 React 中去抖动 Axios POST 请求

[英]Debounce Axios POST requests in React

I'm building a colour picker application in React.我正在 React 中构建一个颜色选择器应用程序。 It sends a POST request containing the HEX value to the backend, every time the colour changes.每次颜色变化时,它都会向后端发送一个包含 HEX 值的 POST 请求。 And it works fine.它工作正常。 The problem is that after it reaches the maximum number of requests per minute, it throws a 429 error: message: "Too Many Attempts."问题是在达到每分钟最大请求数后,会抛出429错误: message: "Too Many Attempts." The goal is to limit the requests to 60 per minute.目标是将请求限制为每分钟 60 个。

I've tried using a package library called axios-rate-limit and here's the code:我尝试使用名为axios-rate-limit的 package 库,代码如下:

import Axios from 'axios'
import rateLimit from 'axios-rate-limit'

export const sendRequest = (param) => {
  const request = rateLimit(Axios.create(), { maxRequests: 60, perMilliseconds: 60000 })
  request
    .post(URL, { colour: param })
    .then(response => console.log(response.data))
    .catch(e => console.log(e))
}

I've also tried lodash's debounce but I'm not sure I'm implementing it correctly?我也尝试过 lodash 的 debounce,但我不确定我是否正确实施它?

import Axios from 'axios'
import _ from 'lodash'

export const sendRequest = param => {
  const request = _.debounce(() => {
    Axios.post(URL, { colour: param })
      .then(response => console.log(response.config))
      .catch(e => console.log(e))
  }, 60000)
  request()
}

The sendRequest function then gets imported into the React component and launches in the useEffect hook like this:然后将sendRequest function 导入 React 组件并在 useEffect 挂钩中启动,如下所示:

import { sendRequest } from './sendRequest'

 useEffect(() => {
        const targetEl = document.querySelector('.js_colourPicker')
        new ReinventedColorWheel({
          appendTo: targetEl,
          //the onChange method triggers every time the colour changes on the colour wheel
          onChange: color => { 
            let colour = HSLToHex(color.hsl[0], color.hsl[1], color.hsl[2])
            sendRequest(colour)
          }
        })
      }, [])

Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks.谢谢。

What you are looking for is throttle and not debounce .您正在寻找的是throttle而不是debounce

Debouce delayes the function call by a duration and cancels the previous call if the function is called again.如果再次调用Debouce ,Debouce 将 function 调用延迟一段时间并取消前一个调用。

Throttle rate limits your function call by allowing only one call per duration specified. Throttle速率限制您的 function 调用,每个指定的持续时间只允许一个调用。

Use it something like this.像这样使用它。

const yourFn = (param) => {
    // do something
}

const throttledYourFn = _.throttle(yourFn, 1000);

Now, when you want to use your yourFn with something like yourFn('param') , use it like this throttledYourFn('param') .现在,当您想将yourFn与类似yourFn('param')东西一起使用时,可以像这样使用它throttledYourFn('param')

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

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