想像一下,我有一個像這樣的對像數組:
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>
)
我想currentItemIndex
每 5 秒更新一次,以便div
顯示下一個項目,如果它結束,它應該重新開始:0, 1, 2, 0, 1, 2, 0, 1, 2 ...
。
問題是:它第一次正確循環,但到達結尾後,它顯示第一項幾分之一秒,然後轉到最後一項:0, 1, 2, 0 (really quick to) 2
。
我做錯了什麼?
我搜索了這個,但每篇文章都在談論“如何防止無限循環”,而不是“如何使用它們”!
你可以像這樣使用useEffect
和使用setTimeout
它:
const items = [{ name: "item 0" }, { name: "item 1" }, { name: "item 2" }];
const App = () => {
const [currentItemIndex, setCurrentItemIndex] = React.useState(0);
React.useEffect(() => {
setTimeout(
() => setCurrentItemIndex((currentItemIndex + 1) % items.length),
1000
);
}, [currentItemIndex]);
return (
<div>
<p> {items[currentItemIndex].name} </p>
</div>
);
};
// export default App;
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句