Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 导航离开后间隔未清除_Javascript_Reactjs_React Hooks - Fatal编程技术网

Javascript 导航离开后间隔未清除

Javascript 导航离开后间隔未清除,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,在我的react web应用中导航到一个新页面后,我注意到它继续根据我的api记录获取请求。我尝试添加一点来清除它,就像在类组件上卸载组件一样,但它仍然以设置的间隔记录 有人能给我提个建议吗 我试过看其他的问题,我试过的似乎是答案,但它不起作用 useEffect(() => { const fetchData = async () => { setIsError(false); try { const res = await fet

在我的react web应用中导航到一个新页面后,我注意到它继续根据我的api记录获取请求。我尝试添加一点来清除它,就像在类组件上卸载组件一样,但它仍然以设置的间隔记录

有人能给我提个建议吗

我试过看其他的问题,我试过的似乎是答案,但它不起作用

useEffect(() => {
    const fetchData = async () => {
      setIsError(false);

      try {
        const res = await fetch(`http://xxxx`, {
          method: "POST",
          mode: "cors",
          headers: {
            "content-type": "application/json",
            credentials: "include"
          }
        });
        res.json().then(res => setApiResponse(res));
      } catch (error) {
        setIsError(true);
      }

      setIsLoading(false);
    };

    fetchData();

    setInterval(fetchData, 3000);
    return () => clearInterval(fetchData);
  }, []);
我希望它清除间隔并停止“泄漏”

clearInterval希望引用setInterval返回的间隔函数,而不是调用它的函数:

useEffect(() => {
    let interval;

    const fetchData = async () => {
      setIsError(false);

      try {
        const res = await fetch(`http://xxxx`, {
          method: "POST",
          mode: "cors",
          headers: {
            "content-type": "application/json",
            credentials: "include"
          }
        });
        res.json().then(res => setApiResponse(res));
      } catch (error) {
        setIsError(true);
      }

      setIsLoading(false);
    };

    fetchData();

    interval = setInterval(fetchData, 3000); // save the id if the interval
    return () => clearInterval(interval);
  }, []);