在react中面临去抖动概念的问题

问题描述 投票:0回答:1
import React,{useState} from 'react';

const app = () =>{
    const [inputValue,setInputValue] = useState();    

    const handleChange = (e)=>{
        setInputValue(e.target.value);
        console.log(inputValue);
    }

    const debounce =function (fn , d) {
        let timer;
        return function(){
            let context = this,
                args=arguments;
        clearTimeout(timer);
          timer = setTimeout(() =>{
              fn.apply(context,args)
          },d)      
        }
    }
    
    const betterFunction = debounce(handleChange, 300);
    
    return (
    <>
        <input type='text' value={inputValue} onChange={betterFunction}/>
        <div>{inputValue}</div>
    </>
    )
    
}

export default app;

在上面的代码中,一旦在

inputfield
中输入任何内容,我就无法进行任何更改。基本上更新
inputfield
卡住了。请帮忙推理并提前感谢您。

javascript reactjs react-hooks debouncing
1个回答
0
投票

或者你可以使用 useDebounce

 包的 
ahooks
 钩子。

import { useState } from 'react';
import { useDebounce } from 'ahooks';

function App() {
  const [inputValue, setInputValue] = useState<string>();
  const debouncedValue = useDebounce(inputValue, { wait: 500 });

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <div>{debouncedValue}</div>
    </>
  );
}

export default App;

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.