在 React 中,如何处理事件的节流(throttling)和防抖(debouncing)?请分别提供实现示例并讨论它们的应用场景。

在React中处理事件的节流(throttling)和防抖(debouncing)是为了优化性能,防止因频繁触发的事件(如窗口缩放、滚动、按键等)导致的性能问题。节流是指在一段时间内只执行一次函数,而防抖是在最后一次操作后的一段时间内,如果不再有新的操作,才执行函数。

节流(Throttling)

应用场景

  • 窗口大小调整(resize事件)
  • 滚动事件(scroll事件)
  • 频繁的网络请求

实现示例

import React, { useEffect } from 'react';

function throttle(func, wait) {
  let timeout = null;
  let lastTime = 0;

  return function(...args) {
    const now = Date.now();
    const remaining = wait - (now - lastTime);

    if (remaining <= 0) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      func.apply(this, args);
      lastTime = now;
    } else if (!timeout) {
      timeout = setTimeout(() => {
        func.apply(this, args);
        lastTime = now + remaining;
        timeout = null;
      }, remaining);
    }
  };
}

function App() {
  const handleResize = () => {
    console.log('窗口大小改变', window.innerWidth, window.innerHeight);
  };

  useEffect(() => {
    const throttledHandleResize = throttle(handleResize, 1000);
    window.addEventListener('resize', throttledHandleResize);

    return () => {
      window.removeEventListener('resize', throttledHandleResize);
    };
  }, []);

  return <div>调整窗口大小查看节流效果</div>;
}

export default App;

防抖(Debouncing)

应用场景

  • 输入框文本改变(input事件)
  • 按钮点击(防止重复点击)
  • 窗口大小调整(resize事件)

实现示例

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

function debounce(func, wait) {
  let timeout;

  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

function App() {
  const [inputValue, setInputValue] = useState('');

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

  const handleSearch = () => {
    console.log('搜索关键字:', inputValue);
  };

  useEffect(() => {
    const debouncedHandleSearch = debounce(handleSearch, 1000);
    const handleInput = (e) => {
      handleChange(e);
      debouncedHandleSearch();
    };

    document.getElementById('searchInput').addEventListener('input', handleInput);

    return () => {
      document.getElementById('searchInput').removeEventListener('input', handleInput);
    };
  }, []);

  return <input id="searchInput" type="text" placeholder="输入搜索关键字" />;
}

export default App;

总结

  • 节流适用于事件触发频率高但不需要立即响应的场景,如窗口调整大小、滚动等。
  • 防抖适用于事件触发后需要一段时间稳定再执行的场景,如输入框的搜索、按钮点击等。