执行自动完成的组件。 当输入 API 请求时发送,所以我添加了一个防抖器。 在防抖器内设置 inputValue 时,防抖器不会执行。
const SearchComp = ({
autoCompleteRes,
classes,
currCondtionsForSelectedAction,
forecastForSelectedAction,
searchAction,
}) => {
const [ inputValue, setInputValue] = useState('Tel aviv')
const changeText = (e) => {
const searchTerm = e.target.value.trim()
if( searchTerm === ('' || undefined)) {
clearSearchAction()
return
}
searchAction(searchTerm)
}
const debounce = (func) => {
let debouncerTimer;
return function(e){
setInputValue(e.target.value) // if i comment this line
const context = this;
const args = arguments;
clearTimeout(debouncerTimer);
e.persist()
debouncerTimer = setTimeout(() => {
return func.apply(context,args)},1500)
}
}
const onClickedRes = (selected) => {
setInputValue(`${selected.LocalizedName}, ${selected.AdministrativeArea.LocalizedName} ${selected.Country.LocalizedName}`)
forecastForSelectedAction(selected);
currCondtionsForSelectedAction(selected);
}
return (
<div className={classes.root}>
<div className={classes.inputWrapper}>
<input type="text" className={classes.inputStyle} name="firstname"
value={inputValue} // and comment this line the debouncer works
onChange={debounce(changeText)}
/>
<div className={classes.dropDownContent}>
{autoCompleteRes.map(item => (
<div
key={item.Key}
className={classes.autoCompleteSingleRes}
onClick={() => onClickedRes(item) }
>
{`${item.LocalizedName}, ${item.AdministrativeArea.LocalizedName} ${item.Country.LocalizedName}`}
</div>))}
</div>
</div>
</div>
)
;}
我不是调用一次changeText函数,而是调用每一次键盘敲击。
不确定发生了什么以及如何解决。
谢谢
最佳答案
通过将 debounce 函数放在功能组件中,它会在每次渲染时重新创建该函数(每次击键都会导致重新渲染),并将新创建的 debounce
函数应用到您的 更改文本
。
您可以在这里采取几种方法:
1) 将 debounce
函数移到组件之外,以便它在渲染之间具有幂等性。这意味着您将 setInputValue
等放入传递给 debounce 的 func
参数中,因为它们现在不在范围内。
2) 将您的 debounce
函数包装在 React.useCallback
中,这将记住 debounce
,因此它不会在渲染之间发生变化,除非依赖项它依赖于更改 (setinputValue
)。
关于reactjs - 在其中设置状态时去抖动不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57241100/