react防抖节流
防抖
import React, { useState, useEffect } from 'react';
const DebounceExample = () => {
const [inputValue, setInputValue] = useState('');
useEffect(() => {
const delay = 1000; // 设置防抖延迟时间为1秒
const timer = setTimeout(() => {
// 在延迟时间结束后执行相应操作,比如发送请求等
console.log('Debounced input value:', inputValue);
}, delay);
return () => {
clearTimeout(timer); // 在每次重新渲染前清除上一次的定时器
};
}, [inputValue]);
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
return (
<div>
<input type="text" onChange={handleInputChange} placeholder="Type something..." />
</div>
);
};
export default DebounceExample;
节流
import React, { useState, useEffect } from 'react';
const ThrottleExample = () => {
const [clickCount, setClickCount] = useState(0);
const [throttled, setThrottled] = useState(false);
const handleClick = () => {
if (!throttled) {
setClickCount(prevCount => prevCount + 1);
setThrottled(true);
}
};
useEffect(() => {
const delay = 1000; // 设置节流时间间隔为1秒
const timer = setTimeout(() => {
setThrottled(false);
}, delay);
return () => {
clearTimeout(timer); // 在每次重新渲染前清除上一次的定时器
};
}, [throttled]);
return (
<div>
<button onClick={handleClick}>Click me</button>
<p>Click count: {clickCount}</p>
</div>
);
};
export default ThrottleExample;
本文来自博客园,作者:zjxgdq,转载请注明原文链接:https://www.cnblogs.com/zjxzhj/p/18108612

浙公网安备 33010602011771号