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;

  

posted @ 2024-04-01 15:43  zjxgdq  阅读(40)  评论(0编辑  收藏  举报