18910140161

JavaScript-React在useEffect中丢失变量?-堆栈溢出

顺晟科技

2022-10-19 14:20:36

260

我正在尝试实现一个图像幻灯片。setInterval在useEffect中用于在x秒后更改图像。currentImage状态保持当前图像,x秒后它将转换为下一个图像,但react告诉我,索引变量将在每次呈现后丢失。

  const images = [one, two, three, four, five, six, seven];

  const [currentImage, setCurrentImage] = React.useState();

  let index = 0;

  useEffect(() => {
    setInterval(() => {
      if (index < images.length) {
        setCurrentImage(images[index]); 
        index++; 
        console.log(images[index]);
      } else {
        index = 0; // If so, reset the index
      }
    }, 5000);
  }, []);


<Grid
      item
      xs={false}
      sm={4}
      md={7}
      sx={{
        backgroundImage: `url(${currentImage})`,
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        backgroundPosition: "center",
      }}
    ></Grid>

从React Hook React.useEffect内部对“index”变量的赋值将在每次呈现后丢失。若要随时间保留该值,请将其存储在useRef钩子中,并将可变值保留在'.current'属性中。否则,可以直接在react.useEffect中移动该变量


顺晟科技:

使用setTimeout并在UseEffect的依赖项数组中添加索引。在该setTimeout中,您将更新索引。但是不要将索引存储为变量,而是将其存储在状态中。

只需使用useState更改索引,并记住清除计时器。

  const images = [one, two, three, four, five, six, seven];

  const [currentImage, setCurrentImage] = React.useState();

  let index = 0;

  useEffect(() => {
    setInterval(() => {
      if (index < images.length) {
        setCurrentImage(images[index]); 
        index++; 
        console.log(images[index]);
      } else {
        index = 0; // If so, reset the index
      }
    }, 5000);
  }, []);


<Grid
      item
      xs={false}
      sm={4}
      md={7}
      sx={{
        backgroundImage: `url(${currentImage})`,
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        backgroundPosition: "center",
      }}
    ></Grid>

还可以这样做:

  const images = [one, two, three, four, five, six, seven];

  const [currentImage, setCurrentImage] = React.useState();

  let index = 0;

  useEffect(() => {
    setInterval(() => {
      if (index < images.length) {
        setCurrentImage(images[index]); 
        index++; 
        console.log(images[index]);
      } else {
        index = 0; // If so, reset the index
      }
    }, 5000);
  }, []);


<Grid
      item
      xs={false}
      sm={4}
      md={7}
      sx={{
        backgroundImage: `url(${currentImage})`,
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        backgroundPosition: "center",
      }}
    ></Grid>
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航