[英]Debounce function in react js functional component
I tried to implement the debounce functionality in the react functional component.我试图在反应功能组件中实现去抖动功能。 But due to some reason, it is not working.
但由于某种原因,它不起作用。
import React from "react";
import "./styles.css";
export default function App() {
const [random, setRandom] = React.useState(Math.random());
const changeKey = () => {
setRandom(Math.random());
};
const debounce = (func, timeout = 1000) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button
onClick={() => {
debounce(changeKey(), 2000);
}}
>
<p>Click Me!</p>
</button>
{random}
</div>
);
}
here I have added the codesandbox link https://codesandbox.io/s/silent-silence-6i532c?file=/src/App.js:0-857在这里我添加了代码框链接https://codesandbox.io/s/silent-silence-6i532c?file=/src/App.js:0-857
Consider implementing it with a hook.考虑用钩子实现它。 This one,
useDebounce
from react-use
is very good.这个,
react-use
中的useDebounce
非常好。 https://github.com/streamich/react-use/blob/master/docs/useDebounce.md https://github.com/streamich/react-use/blob/master/docs/useDebounce.md
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.