Perform debounce in React.js

前端 未结 30 1929
礼貌的吻别
礼貌的吻别 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:26

    Just another variant with recent react and lodash.

    class Filter extends Component {
      static propTypes = {
        text: PropTypes.string.isRequired,
        onChange: PropTypes.func.isRequired
      }
    
      state = {
        initialText: '',
        text: ''
      }
    
      constructor (props) {
        super(props)
    
        this.setText = this.setText.bind(this)
        this.onChange = _.fp.debounce(500)(this.onChange.bind(this))
      }
    
      static getDerivedStateFromProps (nextProps, prevState) {
        const { text } = nextProps
    
        if (text !== prevState.initialText) {
          return { initialText: text, text }
        }
    
        return null
      }
    
      setText (text) {
        this.setState({ text })
        this.onChange(text)
      }
    
      onChange (text) {
        this.props.onChange(text)
      }
    
      render () {
        return ( this.setText(event.target.value)} />)
      }
    }
    

提交回复
热议问题