我正在尝试为我的应用程序添加字幕,这是我用React编写的。
我一直在尝试使用setTimeout,如下所示。它在一开始就像它应该的那样运行。
const [paragraphs] = useState(IntroContent.intro.paragraphs);
const [displayParagraph, setDisplayParagraph] = useState("");
const [index, setIndex] = useState(0);
const timeoutDelays = [0, 5000, 4000, 5000, 5000, 11000, 10000, 7000, 0];
const changeParagraph = () => {
setDisplayParagraph(paragraphs[index]);
setIndex(index + 1);
}
setTimeout(changeParagraph, timeoutDelays[index]);字幕以足够接近的时间滚动,但当滚动到第三个字幕时,它们开始转到前一个字幕,然后在间隔后再次切换到正确的字幕,然后继续这样做,直到结束。
我试过clearTimeout,但它不能解决我的问题。
发布于 2020-09-10 02:14:26
因为您已经对每个索引调用了2次setState (setDisplayParagraph和setIndex),所以它将重新呈现2次,也会调用setTimeout 2次。您应该在使用useEffect呈现组件之后调用函数setTimeout,并且应该只在index发生变化时调用:
useEffect(() => {
setTimeout(changeParagraph, timeoutDelays[index]);
}, [index])https://stackoverflow.com/questions/63817103
复制相似问题