Rxjs debounce on react text input component

后端 未结 3 810
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 06:41

I have the following react component



        
3条回答
  •  难免孤独
    2020-12-16 07:03

    You will need to cretae observable from change events(for example using Subject) and then debounce on that.

    Here is the fully featured example for you:

    class Search extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          search: '',
          debounced: '',
        };
        this.onSearch$ = new Rx.Subject();
        this.onSearch = this.onSearch.bind(this);
      }
      componentDidMount(){
        this.subscription = this.onSearch$
          .debounceTime(300)
          .subscribe(debounced => this.setState({ debounced }));
      }
      
      componentWillUnmount() {
        if (this.subscription) {
          this.subscription.unsubscribe();
        }
      }
      
      onSearch(e) {
        const search = e.target.value;
        this.setState({ search });
        this.onSearch$.next(search);
      }
    
      render() {
        const { search, debounced } = this.state;
        return (
          
    debounced value: {debounced}
    ); } } ReactDOM.render( , document.getElementById('root') );
    
    
    
    

提交回复
热议问题