【发布时间】:2021-11-26 01:25:21
【问题描述】:
我正在尝试实现图像幻灯片。 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 Hook 中,并将可变值保留在 '.current' 属性中。否则,你可以直接在 React.useEffect 中移动这个变量
【问题讨论】:
标签: javascript html reactjs react-hooks frontend