Rxjs debounce on react text input component

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

I have the following react component



        
3条回答
  •  Happy的楠姐
    2020-12-16 07:14

    I agree with the example by Oles Savluk. In addition, I would extract the Subject logic out of the component. It doesn't need to live inside the component, as it has no state, and I think this also makes the component easier to understand.

    Also: The example is updated to use RxJS 6.2.2

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

提交回复
热议问题