Rxjs debounce on react text input component using Subjects does not batch input text on stateless/functional component

混江龙づ霸主 提交于 2020-01-21 10:27:21

问题


I'm trying to dive deeper into rxjs and found an issue where the input field I'm trying to debounce dispatches an event on every keypress, the debounce only holds the output but results in a tree like:

a
as(delay - waits 200ms, then fires the rest synchronously)
asd
asdf
asdfg 
....

The same code works as expected in a class component(https://stackoverflow.com/a/44300853/1356046) but cannot understand why it doesn't work with stateless components. Here's an example: https://stackblitz.com/edit/react-hzhrmf - you can see the useState update fires for every keystroke.

Thanks a lot.


回答1:


React continuously calls your function to render the component. Therefore the Subject is continuously recreated.

Using a factory with useState to keep the subject and working with useEffect to make sure the subscription is only made once should fix your issue.

Something like this :

import React, { Component, useState, useEffect, useRef } from 'react';
import { render } from 'react-dom';
import { debounceTime, map, tap, distinctUntilChanged } from 'rxjs/operators';
import { fromEvent, Subject } from 'rxjs';

import './style.css';
const App = props => {
  const [queryName, setQueryName] = useState("");
  const [debouncedName, setDebouncedName] = useState("");
  const [onSearch$] = useState(()=>new Subject());
  useEffect(() => {
    const subscription = onSearch$.pipe(
      debounceTime(400),
      distinctUntilChanged(),
      tap(a => console.log(a))
    ).subscribe(setDebouncedName);
  }, [])
  const handleSearch = e => {
    setQueryName(e.target.value);
    onSearch$.next(e.target.value);
  };

  return (
    <div>
      <input
        placeholder="Search Tags"
        value={queryName}
        onChange={handleSearch}
      />
      <p>Debounced: {debouncedName}</p>
    </div>
  );
}

render(<App />, document.getElementById('root'));


来源:https://stackoverflow.com/questions/58520864/rxjs-debounce-on-react-text-input-component-using-subjects-does-not-batch-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!