首页 > 解决方案 > 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 的那个。

标签: reactjstypescriptasynchronousreact-select

解决方案


我已经解决了这个问题,看来问题出在去抖上。我正在使用debounce-promise,问题是我使用了leading=true 选项,这使得 UI 对更改没有响应。

从这段代码:

this.debouncedLoadQuery = debounce(loadOptions, 2000, {
  leading: true,
});

对此代码:

this.debouncedLoadQuery = debounce(loadOptions, 2000);

推荐阅读