【问题标题】:How to add Lodash debounce to react input?如何添加 Lodash debounce 以响应输入?
【发布时间】:2021-12-13 18:39:38
【问题描述】:

我有一个简单的形式:

https://codesandbox.io/s/distracted-poincare-2blfq?file=/src/App.js:357-552

      <form>
        <TextField
          onChange={handleChange}
          onBlur={clearInput}
          value={inputValue}
          placeholder="Do an api request"
        />
      </form>

onChange 上,我想使用输入的值执行 api 请求,但我想添加一个去抖动或节流。重要的是,当输入模糊时,输入中的文本应该被删除并且占位符应该是可见的。

【问题讨论】:

    标签: reactjs lodash


    【解决方案1】:

    方法 1.

    使用React去抖输入,简单方法

    https://www.npmjs.com/package/react-debounce-input

    方法 2

    基于此创建计时器并调用 API,无需外部库。我总是建议这个

     let timer = null
     const handleChange = (e) => {
        setInputValue(e.target.value)
        if(timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(()=>yourApiCall(e.target.value), 700)
     }
     const yourApiCall = (val) => {
       //call API here
     }
    
      <form>
        <TextField
          onChange={handleChange}
          onBlur={clearInput}
          value={inputValue}
          placeholder="Do an api request"
        />
      </form>
    

    一个工作示例

    https://codesandbox.io/s/beautiful-goldberg-vyo2u?file=/src/App.js

    方法 3

    使用 loadash 去抖动

    查看此链接的答案

    Lodash debounce with React Input

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2019-04-08
      相关资源
      最近更新 更多