[英]How to debounce a function?
I'm trying to set a timer for onChange but I don't understand why it doesn't work.我正在尝试为 onChange 设置一个计时器,但我不明白为什么它不起作用。 I tried several methods, but none worked.
我尝试了几种方法,但都没有奏效。 What can I change to make it work?
我可以更改什么以使其工作?
import React, {useState} from 'react'
import { debounce } from "lodash";
const Search = ({getQuery}) => {
const [text, setText] = useState('')
const onChange = (q) => {
setText(q)
getQuery(q)
}
const handleDebounce = () => {
debounce(onChange, 3000);
};
return (
<section className='search'>
<form>
<input
type='text'
className='form-control'
placeholder='Search characters'
value={text}
onChange={(e) => handleDebounce( onChange(e.target.value), 3000)}
autoFocus
/>
</form>
</section>
)}
export default Search
removce handleDebounce
completely and call your own onChange
at the input onChange
removce
handleDebounce
完全和调用自己onChange
在输入onChange
onChange={onChange}
then adjust your onChange
implementation as:然后将您的
onChange
实现调整为:
const onChange = (e) => {
const query = e.target.value;
setText(query);
debounce(() => getQuery(query), 3000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.