reactjs - React : 当用户停止输入时触发函数
问题描述
我正在使用带有异步创建表的 react-select 并将其实现到 Netsuite 自定义页面。问题是我想加载 getAsyncOptions 函数以仅在用户停止键入时触发。目前,这些代码行使输入字段变得如此缓慢,因为每次将字母添加到输入中时都会触发该功能。我也无法将获取的数据插入状态,因为它将填充一千条记录。
电子邮件.tsx
getAsyncOptions(inputValue) {
return new Promise((resolve) => {
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms (1 second)
if (inputValue.length <= 3) {
return resolve([]);
}
clearTimeout(typingTimer);
if (inputValue) {
return (typingTimer = setTimeout(function () {
var t0 = performance.now();
emailSearch(inputValue).then((data) => {
const returnData = [];
data.forEach((contact) => {
returnData.push({
label: contact.email + " - (" + contact.company + ")",
value: contact.email,
});
});
resolve(returnData);
console.log(
"Call to email search function took " +
(t1 - t0) +
" milliseconds."
);
});
var t1 = performance.now();
}, doneTypingInterval));
}
});
正如您在上面的代码中看到的,它只是延迟代码触发。当用户停止输入 1 秒并继续输入时,会出现另一个问题,它只是延迟功能,并且每 1 秒触发一次。这是其余的代码供您参考。
渲染打开模式.tsx
<AsyncCreatableSelect
value={props.state.toEmailCollection}
onChange={props.setToEmail}
loadOptions={props.debouncedLoadQuery}
styles={props.customSelectStylesEmail}
components={{
DropdownIndicator: () => null,
IndicatorSeparator: () => null,
}}
isMulti={true}
isSearchable={true}
isValidNewOption={props.isValidNewOption}
placeholder=""
/>
功能
this.setToEmail = (toEmailCollection) =>
this.setState({ toEmailCollection: toEmailCollection });
this.setToCc = (toCcCollection) =>
this.setState({ toCcCollection: toCcCollection });
const loadOptions = (inputValue) => this.getAsyncOptions(inputValue));
this.debouncedLoadQuery = debounce(loadOptions, 2000, {
leading: true,
});
一段时间以来一直面临这个障碍,非常感谢任何想法或帮助!非常感谢你,上帝保佑!
编辑:添加了一些代码。onChange 仅更新某些状态,问题在于 loadOptions,因为它是触发 getAsyncOptions 的那个。
解决方案
我已经解决了这个问题,看来问题出在去抖上。我正在使用debounce-promise,问题是我使用了leading=true 选项,这使得 UI 对更改没有响应。
从这段代码:
this.debouncedLoadQuery = debounce(loadOptions, 2000, {
leading: true,
});
对此代码:
this.debouncedLoadQuery = debounce(loadOptions, 2000);
推荐阅读
- azure - 如何强制在 Azure 中的所有新 VM 上运行 powershell 脚本扩展?
- assembly - clflush 是否刷新 L1i?
- java - 您好,我想使用蓝牙 iBeacon 进行检测,但效果不佳。我该如何解决?
- node.js - 为什么我的 Heroku API 应用程序不返回 json 数据?
- html - 在没有 flex 的情况下在一行中对齐 Div,因为它会弄乱高度(Bootstrap)
- apache-spark - 在 PySpark 中转换数据框模式
- python - 操作许多不同绘图的 matplotlib 图形组件的最有效方法是什么?
- c# - WPF 滑块可在单击时更改按钮颜色
- python - 如何在熊猫图中增加 xticks 的大小
- xml - 第二次创建片段时,片段中的视图相互重叠