钩子useEffect和settimeout

时间:2020-02-06 14:10:46

标签: reactjs

你好,我对useEffect的逻辑有疑问,我不知道我是否很好理解.. 我正在使用redux,并且在发送消息时,我在reducer上设置了waitResponse = = true,然后在此useEffect中进行了此操作:

 const ChatReducer = useSelector(state => state.Chat);
 const [isTyping, setIsTyping] = useState(false);
 const [hasResponded, setHasResponded] = useState(false);

 useEffect(() => {
    // Notice the change here checking if we have already responded
    // The if statement now surrounds the timeout and the interval
    // This prevents any of these actions from happening once the response  has been made
    setHasResponded(false);
    if (ChatReducer.waitResponse === true && !hasResponded) {
      setIsTyping(true);
      const timeoutId = setTimeout(() => {
        console.log('aeee');
        setHasResponded(true);
        dispatch(wait_end());
        setIsTyping(false);
      }, 3000);
      return () => clearTimeout(timeoutId);
    }
  }, [ChatReducer.waitResponse, hasResponded]);

基本上,如果我连续发送2个文本,则一次不会输入2次timout:

enter image description here

0 个答案:

没有答案