用Debounce延迟React组件的渲染 - react-bouncer

759 阅读1分钟

Delay Rendering Of A React Component With Debounce

react-bouncer是一个组件库,它用debounce、throttle或任何其他延迟渲染方法包装组件,以阻止它们在道具变化时经常重新渲染。

如何使用它

1.安装并导入。

# NPM
$ npm i @yaireo/react-bouncer
import bouncer from '@yaireo/react-bouncer'

2.基本使用方法。

// simplified example for a component which gets rendered often due to props change
const Foo = ({x,y}) => `${x} ${y}`;
// uses 300ms `debounce` by default
const DebouncedFoo = bouncer(Foo)
DebouncedFoo.displayName = 'DebouncedFoo';

// use a `throttle` method instead of the default `debounce` (or use your own custom one)
const ThrottleddFoo = bouncer(Foo, 300, throttle)
DebouncedFoo.displayName = 'ThrottleddFoo';

// use them in another component which might render them often with different props
const App = () => {
  const [pos, setPos] = useState({x:0, y:0})
  // re-render on mouse move
  useEffect(() => {
    const onMouseMove = e => setPos({x: e.pageX, y: e.pageY})
    window.addEventListener('mousemove', onMouseMove)
    return () => window.removeEventListener('mousemove', onMouseMove)
  }, [])
  return <>
      <DebouncedFoo {...pos}/>
      <ThrottleddFoo {...pos}/>
  </>
}

预览

Delay Rendering Of A React Component With Debounce

The postDelay Rendering Of A React Component With Debounce - react-bouncerappeared first onReactScript.