每 5 秒调用一次 onChange 函数

时间:2021-04-10 19:17:02

标签: javascript reactjs

我有一个有效的代码,当我更改一些文本时运行

import React, { useState } from "react";


const onChange = async ({ target: { value, name } }) => {
    setErrors({ ...errors, [name]: false });
    setUserData({ ...userData, [name]: value });

    if (name === "address") {
      const res = await searchAddress(value);
      if (res.success) {
        setAddressList(res?.results?.matches || []);
      }
    }
  };

如何仅在发生文本更改且上次调用晚于 5 秒时才执行 searchAddress?

2 个答案:

答案 0 :(得分:1)

您可以为此使用 debouce

import React, { useState, useCallback } from "react";



const onChange = async ({ target: { value, name } }) => {
  setErrors({ ...errors, [name]: false });
  setUserData({ ...userData, [name]: value });

const searchAddress = useCallback(debounce(async (value)=> await searchAddress(value), 5000), []);

  if (name === "address") {
    const res = await searchAddress(value);
    if (res.success) {
      setAddressList(res?.results?.matches || []);
    }
  }
};

答案 1 :(得分:0)

您可以为此使用外部库,例如 lodash 的油门,但也可以通过简单的 settimeout 实现。

let timer; //declare the timer variable outside the component

const App = () => {
    ...declare useState here..

const onChange = async ({ target: { value, name } }) => {
    setErrors({ ...errors, [name]: false });
    setUserData({ ...userData, [name]: value });

    if (name === "address") {
      clearTimeout(timer) //clear the timeout on every change.
      timer = setTimeOut(() => { //create a timeout to the timer variable so u can clear it
      const res = await searchAddress(value);
      if (res.success) {
        setAddressList(res?.results?.matches || []);
      }
       }, 5000) 
    }
  };

   return .....
}

如果您正在执行自动完成,5000 是一个非常长的时间并且不利于用户体验,200-500 毫秒的超时会很好,因为每次击键都会清除超时。

使用 200-500 超时意味着只有在用户暂停输入 200-500 毫秒而不是每次击键时才会获取 API。

相关问题