使用去抖动的onChange处理函数设置输入值 [英] Set input value with a debounced onChange handler
问题描述
在我的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屋!