Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/11.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
Reactjs 无法停止useEffect挂钩中的内存泄漏,请执行以下操作:_Reactjs - Fatal编程技术网

Reactjs 无法停止useEffect挂钩中的内存泄漏,请执行以下操作:

Reactjs 无法停止useEffect挂钩中的内存泄漏,请执行以下操作:,reactjs,Reactjs,我有一个登陆页面,在下面的反应功能改变图像在旋转木马 当我离开后,它给出错误“无法对未安装的组件执行反应状态更新”。 下面的功能每2秒钟更改一次转盘图像 // state to find idex const [imageIndex, setImageIndex] = React.useState(0); //array of images to display const images = [ image1,image3,image2, ]; /

我有一个登陆页面,在下面的反应功能改变图像在旋转木马

当我离开后,它给出错误“无法对未安装的组件执行反应状态更新”。

下面的功能每2秒钟更改一次转盘图像

  // state to find idex
  const [imageIndex, setImageIndex] = React.useState(0); 

  //array of images to display
  const images =  [
  image1,image3,image2,
    ];
    
  //function that changes image index in every 2 second
  const nextImage = () => {
    setImageIndex((prev) => (prev + 1) % images.length);
    setTimeout(nextImage, 2000);
  };

  // function to initiate above function, the memory leak happens here
  React.useEffect(nextImage, []);
我已经通过了一些StackOverflow问题,并更改了我的计时功能,如下所示,但错误仍然存在

// useEffect triggers this functions

const nextImage = () => {
    let unmounted = false;
    if (!unmounted) {
      setImageIndex((prev) => (prev + 1) % images.length);
      setTimeout(nextImage, 2000);
    }

    return () => {
      unmounted = true;
    };
  };


我提到的问题有答案,但我没有弄清楚。这里我为您创建了一个简单的片段。希望你能理解这一点。由于您使用的是
setTimeout
,请确保您也使用了
cleartimout
。并在图像索引更改时重新运行效果

const{useState,useffect}=React;
功能测试(){
常量[imageIndex,setImageIndex]=React.useState(0);
常量图像=['image1'、'image2'、'image3'];
useffect(()=>{
let timeoutId=setTimeout(()=>{
setImageIndex((imageIndex+1)%images.length);
}, 2000);
return()=>{
clearTimeout(超时ID)
}
},[imageIndex])
返回{images[imageIndex]}
}
ReactDOM.render(
,
document.getElementById('root'))
);

这里我为您创建了一个简单的代码片段。希望你能理解这一点。由于您使用的是
setTimeout
,请确保您也使用了
cleartimout
。并在图像索引更改时重新运行效果

const{useState,useffect}=React;
功能测试(){
常量[imageIndex,setImageIndex]=React.useState(0);
常量图像=['image1'、'image2'、'image3'];
useffect(()=>{
let timeoutId=setTimeout(()=>{
setImageIndex((imageIndex+1)%images.length);
}, 2000);
return()=>{
clearTimeout(超时ID)
}
},[imageIndex])
返回{images[imageIndex]}
}
ReactDOM.render(
,
document.getElementById('root'))
);


如果设置超时,还需要执行clearTimeout如果设置超时,还需要执行clearTimeout