Perform debounce in React.js

前端 未结 30 1610
礼貌的吻别
礼貌的吻别 2020-11-22 04:11

How do you perform debounce in React.js?

I want to debounce the handleOnChange.

I tried with debounce(this.handleOnChange, 200) but it doesn\'t

30条回答
  •  -上瘾入骨i
    2020-11-22 04:50

    With debounce you need to keep the original synthetic event around with event.persist(). Here is working example tested with React 16+.

    import React, { Component } from 'react';
    import debounce from 'lodash/debounce'
    
    class ItemType extends Component {
    
      evntHandler = debounce((e) => {
        console.log(e)
      }, 500);
    
      render() {
        return (
          
    { e.persist() this.evntHandler(e) }}> ...
    ); } } export default ItemType;

    With functional component, you can do this -

    const Search = ({ getBooks, query }) => {
    
      const handleOnSubmit = (e) => {
        e.preventDefault();
      }
      const debouncedGetBooks = debounce(query => {
        getBooks(query);
      }, 700);
    
      const onInputChange = e => {
        debouncedGetBooks(e.target.value)
      }
    
      return (
        
    Search the world's most comprehensive index of full-text books.
    ) }

    References - - https://gist.github.com/elijahmanor/08fc6c8468c994c844213e4a4344a709 - https://blog.revathskumar.com/2016/02/reactjs-using-debounce-in-react-components.html

提交回复
热议问题