【发布时间】:2021-12-26 05:13:54
【问题描述】:
我正在尝试使用 react hooks 和 setInterval 制作 5 张图片的幻灯片。
所以当计数器到达照片 5(索引 4)时,它会返回到照片 1(索引 0)。
计数器看起来没问题,但即使 if 语句中的条件为假,计数器也会一直计数到 4。
import React, { useState, useEffect } from 'react';
import { photoSource } from './photo-source.js';
function Slideshow() {
const [imgSource, setImgSource] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
if (imgSource <= 1) {
setImgSource(imgSource => imgSource + 1);
} else {
setImgSource(0);
}
}, 10000);
return () => clearInterval(intervalId);
}, []);
console.log('ImgSource: ' + imgSource);
console.log(imgSource <= 1)
console.log(photoSource[imgSource].src)
所有记录到控制台的值似乎都是正确的,唯一明显的问题是计数器一直在计数,好像 if 语句不起作用。
【问题讨论】:
标签: reactjs timer react-hooks setinterval