使用去抖动的 onChange 处理程序设置输入值 [英] Set input value with a debounced onChange handler

查看:21
本文介绍了使用去抖动的 onChange 处理程序设置输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 React Hooks 应用程序中,我需要让用户在输入字段中输入 1000 毫秒.当 1000 毫秒到期时,会发送一个带有输入值的 API 请求.

In my React Hooks app I need to let user type to an input field for 1000ms. When 1000ms expire an API request is sent with the input value.

<input type='text' name='name' className='th-input-container__input' onChange={evt => testFunc2(evt.target.value)} />

值在testFunc2(evt.target.value)中设置:

const testFunc2 = useCallback(debounce((text) => setNameFilter(text), 1000), []);

一旦 nameFilter 设置为新值 useEffect 发出 API 请求,因为 nameFilter 是它的依赖项.这样,API 只使用结果用户输入而不是每个键击值来查询,但输入保持不受控制.当我使用 value={nameFilter} 将当前的 nameFilter 值添加到输入中时,用户无法输入到输入中,并且输入仅接收最后输入的字符.

Once nameFilter is set to a new value useEffect issues an API request since nameFilter is its dependency. That way the API is queried with only the resulting user input instead of with each key stroke value but the input stays uncontrolled. When I add the current nameFilter value to the input with value={nameFilter} user cannot type into the input and the input receives only the last typed character.

如何让用户输入的字符显示在输入中?

How do I get the user typed characters to display in the input?

推荐答案

更新答案:

const debouncedApiCall = useCallback(debounce((text) => {
  getRecordsForPage(1, text, '', '', '', '', 10, {});
}, 1000), [])

useEffect(() => {
  debouncedApiCall(nameFilter);
}, [nameFilter, debouncedApiCall])

<input type='text' value={nameFilter} onChange={evt => setNameFilter(evt.target.value)} />

这篇关于使用去抖动的 onChange 处理程序设置输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆