React 中无法使用clearTimeout 清除计时器?

问题描述 投票:0回答:1

这是我的代码

function MyComponent() {
  const [searchTerm, setSearchTerm] = useState('');
  const [results, setResults] = useState('');
  let timeout = null;

  function getFromAPI(userInput) {
      fetch(API_URL).then(response => response.json()).then(data => setResults(data));
  }

  function handleChange(userInput) {
    setSearchTerm(userInput);
    clearTimeout(timeout);
    
    timeout = setTimeout(() => {
      getFromAPI(userInput);
    }, 600);
  }

  return (
       <input value={searchTerm} onChange={e => handleChange(e.target.value)} />
       {results}
  )
}

我想要的是,当用户输入

<input />
时,我们会等待 600 毫秒,然后再调用
fetch()
来获取他们的结果。如果他们在 600 毫秒之前输入另一个字符,我们会清除第一个字符的超时,并使用这两个字符进行
fetch()
调用。

现在,每次用户在

fetch()
中输入内容时,我的代码都会调用
<input />
。换句话说,如果用户快速键入 6 个字符,则应该有 1 个 API 调用,而不是 6 个。问题显然是我的超时没有像我希望的那样被清除。这可能是我的反应组件重新渲染的某种问题吗?或者也许我需要使用
useState()
而不是 do
let timeout = null;

谢谢!

javascript reactjs timer
1个回答
0
投票

问题在于你的变量声明,你使用 let 来声明超时变量,这在反应应用程序中不是一个好习惯。每次组件重新渲染时,变量都会重新初始化,而您应该做的是使用 React 库中的 useRef 钩子来创建可变变量。

import React, { useState, useRef } from 'react';

function MyComponent() {
  const timeoutRef = useRef(null);

  function handleChange(userInput) {
    setSearchTerm(userInput);
    clearTimeout(timeoutRef.current);

    timeoutRef.current = setTimeout(() => {
      getFromAPI(userInput);
    }, 600);
  }

  return (
    <>
    </>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.