【问题标题】:using rxjs debounceTime with react hooks [duplicate]使用带有反应钩子的 rxjs debounceTime [重复]
【发布时间】:2020-01-14 23:58:16
【问题描述】:

我正在尝试将 rxjs debounceTime 与反应挂钩一起使用。这是我到目前为止的代码

const searchFriendSubject = new Subject();
const subscription = searchFriendSubject.pipe(debounceTime(1500)).subscribe(val => {
  console.log('This is the value ', val);
});

const friendComponent = () => {
  const [formData, setSearchTerm] = useState({
    searchTerm: { value: '', valid: true }
  });

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    const formDataToSet = {
      ...formData,
      ...{ searchTerm: { valid: true, value: newValue } }
    };
    setSearchTerm(formDataToSet);
    searchFriendSubject.next(newValue);
  };

  useEffect(() => {
    const subscription = searchFriendSubject.pipe(debounceTime(1500)).subscribe(val => {
      console.log('This is the value ', val);
    });

    return () => {
      subscription.unsubscribe();
    };
  });

  return (
    <FriendSearchComponentStyles.containerBlock>
      <input
        type="text"
        onChange={onChange}
      ></input>
    </FriendSearchComponentStyles.containerBlock>
  );
};

问题是订阅根本没有触发。如果我从effect 中删除subscription.unsubscribe();,则订阅有效,但会触发多次。

【问题讨论】:

  • 谢谢,我会试试看。
  • 感谢这解决了我的问题。

标签: rxjs react-hooks


【解决方案1】:

除了 gojun 提到的重复订阅之外,您的主要问题是您的效果没有依赖数组,因此它会在每次渲染时取消订阅/重新订阅

useEffect(() => {
  const subscription = searchFriendSubject.pipe(debounceTime(1500)).subscribe(val => {
    console.log('This is the value ', val);
  });

  return () => {
    subscription.unsubscribe();
  };
}, []);

如果您只想在挂载时订阅并在卸载时取消订阅,请传递一个空数组。如果您想在这些道具更改时重新订阅,或者传递一些道具值。

【讨论】:

  • 我也试过了,还是不行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 2020-12-05
  • 2021-09-29
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多