Perform debounce in React.js

前端 未结 30 1565
礼貌的吻别
礼貌的吻别 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条回答
  •  名媛妹妹
    2020-11-22 04:46

    I found this post by Justin Tulk very helpful. After a couple of attempts, in what one would perceive to be the more official way with react/redux, it shows that it fails due to React's synthetic event pooling. His solution then uses some internal state to track the value changed/entered in the input, with a callback right after setState which calls a throttled/debounced redux action that shows some results in realtime.

    import React, {Component} from 'react'
    import TextField from 'material-ui/TextField'
    import { debounce } from 'lodash'
    
    class TableSearch extends Component {
    
      constructor(props){
        super(props)
    
        this.state = {
            value: props.value
        }
    
        this.changeSearch = debounce(this.props.changeSearch, 250)
      }
    
      handleChange = (e) => {
        const val = e.target.value
    
        this.setState({ value: val }, () => {
          this.changeSearch(val)
        })
      }
    
      render() {
    
        return (
            
        )
      }
    }
    

提交回复
热议问题