使用rxjs debounceTime和react挂钩

使用rxjs debounceTime和react挂钩,rxjs,react-hooks,Rxjs,React Hooks,我正在尝试将rxjsdebounceTime与react挂钩一起使用。这是我目前掌握的代码 const searchFriendSubject = new Subject(); const subscription = searchFriendSubject.pipe(debounceTime(1500)).subscribe(val => { console.log('This is the value ', val); }); const friendComponent = ()

我正在尝试将rxjs
debounceTime
与react挂钩一起使用。这是我目前掌握的代码

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>
  );
};
const searchFriendSubject=新主题();
const subscription=searchFriendSubject.pipe(debounceTime(1500)).subscription(val=>{
log('这是值',val);
});
常量friendComponent=()=>{
常量[formData,setSearchTerm]=useState({
searchTerm:{值:“”,有效值:true}
});
const onChange=(e:React.ChangeEvent)=>{
const newValue=e.target.value;
常量formDataToSet={
…表格数据,
…{searchTerm:{valid:true,value:newValue}}
};
设置搜索项(formDataToSet);
searchFriendSubject.next(newValue);
};
useffect(()=>{
const subscription=searchFriendSubject.pipe(debounceTime(1500)).subscription(val=>{
log('这是值',val);
});
return()=>{
订阅。取消订阅();
};
});
返回(
);
};

问题是订阅根本无法启动。如果我删除
subscription.unsubscripte()
效果中
则订阅可以工作,但会触发多次

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


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

我也尝试了此方法,但仍然无效。谢谢,我将尝试此方法并查看。谢谢,这解决了我的问题。
useEffect(() => {
  const subscription = searchFriendSubject.pipe(debounceTime(1500)).subscribe(val => {
    console.log('This is the value ', val);
  });

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