【问题标题】:React : Trigger function when the user stops typingReact : 当用户停止输入时触发函数
【发布时间】:2021-07-27 07:31:35
【问题描述】:

我正在使用带有异步创建表的 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 秒触发一次。这是其余的代码供您参考。

RenderOpenMode.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 的那个。

【问题讨论】:

  • 您所追求的称为“去抖动”功能。去抖动是当您延迟执行一个函数,直到它没有被调用一段特定的时间。 stackoverflow.com/questions/15927371/what-does-debounce-do
  • 我已经添加了去抖动,似乎它只是延迟了加载获取的数据。但是在获取数据时,UI 没有响应。不过感谢您的评论!
  • 我最初将此标记为重复,但后来发现您已经在尝试消除 something 的抖动。 “当用户停止输入时触发功能”基本上转化为去抖动onChange 处理程序,或者onChange 处理程序正在更新的任何内容。您能否提供一个更全面的代码示例,以便我们跟踪从onChangeemailSearch 的事件?这answer 有帮助吗?
  • 更新了问题。感谢您的回复!

标签: reactjs typescript asynchronous react-select


【解决方案1】:

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

从此代码:

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

到此代码:

this.debouncedLoadQuery = debounce(loadOptions, 2000);

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 2021-08-20
    • 2021-11-15
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多