【发布时间】:2022-01-04 16:21:31
【问题描述】:
想象一下我有一个这样的对象数组:
const items = [
{name: "item 0"},
{name: "item 1"},
{name: "item 2"}
]
还有一个像这样的组件:
const [currentItemIndex, setCurrentItemIndex] = useState(0)
setInterval(function () {
if (currentItemIndex < 3) {
setCurrentItemIndex(currentItemIndex + 1);
} else {
clearInterval();
}
}, 5000);
return (
<div>
<p> {items[currentItemIndex].name} <p>
</div>
)
我想每 5 秒更新一次 currentItemIndex,以便 div 显示下一项,如果它到达末尾,它应该重新开始:0, 1, 2, 0, 1, 2, 0, 1, 2 ...。
问题是:它第一次循环正确,但到达结尾后,它显示第一个项目不到一秒钟,然后转到最后一个项目:0, 1, 2, 0 (really quick to) 2。
我做错了什么?
我搜索了这个,但每篇文章都在谈论“如何防止无限循环”,而不是“如何使用它们”!
【问题讨论】:
-
而不是
setCurrentItemIndex(currentItemIndex + 1)你可以试试setCurrentItemIndex( val => (val + 1)) -
您需要使用
useEffect来处理setTimeout之类的效果 - 例如stackoverflow.com/questions/57542264/… -
首先,您对clearInterval 的使用是不正确的,并没有做任何事情。其次,您的循环永远不会从头开始,因为您从未重置计数器。
-
您需要将
currentItemIndex移回零的东西,然后您可以继续增加它。因此,您可以像这样添加检查setCurrentItemIndex((currentItemIndex + 1) % items.length); -
@SaadMehmood 好主意。
标签: javascript reactjs