我正在尝试每3秒旋转一次图像,但是图像运行的时间越长,加载速度似乎越快,这就像设置间隔被调用了很多次而不仅仅是一次,我是否需要{{1} }?
useEffect
import React, { useState } from "react";
import image1 from "../images/carousel/screen-1.png";
import image2 from "../images/carousel/screen-2.png";
import image3 from "../images/carousel/screen-3.png";
import image4 from "../images/carousel/screen-4.png";
import image5 from "../images/carousel/screen-5.png";
const Carousel: React.FC = () => {
interface StateInterface {
showImage: string;
startSlide: number;
}
const [state, setState] = useState<StateInterface>({
showImage: image1,
startSlide: 0
});
setInterval(() => {
console.log('Im Starting'); // <== this prints many times, over and over
const images = [image1, image2, image3, image4, image5]
let currentIndex = state.startSlide;
if (currentIndex < 5) currentIndex++;
else currentIndex = 1;
setState({ ...state, showImage: images[currentIndex], startSlide:currentIndex });
}, 3000);
return (
<div className="carousel">
<img src={state.showImage}></img>
</div>
);
};
export { Carousel };
是showImage
还是HTMLObject类型?或类似的??
答案 0 :(得分:1)
您正在尝试从字符串中分配变量。 就像尝试这样做
const x ="Carousel"
x()
只需将所有图像添加到数组中,而不是对其名称进行迭代,即可返回数组中的there索引
并将 startSlide 添加到状态
interface StateInterface {
showImage: string;
startSlide:int
}
setInterval(() => {
const images = [image1, image2, image3, image4, image5]
let currentIndex = this.state.startSlide
if (startSlide < 5) currentIndex++;
else currentIndex = 1;
setState({ ...state, showImage: images[currentIndex], startSlide:currentIndex });
}, 3000);