勾選復選框時,我正在嘗試更新 setInterval 中的 activeIndex 計數。單擊按鈕時,handlenex()and handleprevious()作業正常,但是當檢查復選框時,ActiveIndex的值未在handlenext()中更新(),但是它在螢屏上已更新,因此沒有任何條件檢查ActiveIndex,并且它是它的條件超過3。
import { useState } from "react";
import "./styles.css";
export default function App() {
const [slideTimer, setSlideTimer] = useState(null);
const [activeIndex, setActiveIndex] = useState(0);
const slideDuration = 1000;
const handleNext = () => {
if ((activeIndex) >= 3) {
setActiveIndex(0);
} else {
setActiveIndex(prev => prev 1);
}
};
const handlePrev = () => {
if (activeIndex <= 0) {
setActiveIndex(3);
} else {
setActiveIndex((prev) => prev - 1);
}
};
const toggleSlider = () => {
if (slideTimer) {
clearInterval(slideTimer);
setSlideTimer(null);
return;
}
setSlideTimer(setInterval(handleNext, slideDuration));
};
return (
<div className="App">
<h1>{activeIndex}</h1>
<button onClick={() => handleNext()}>Next</button>
<button onClick={() => handlePrev()}>Previous</button>
<input onClick={() => toggleSlider()} type="checkbox" />
</div>
);
}
我嘗試將 toggleSlider 的代碼放在 useEffect() 中,但這也不起作用。
uj5u.com熱心網友回復:
您的問題是,當handleNext被定義時(發生在每次重新渲染時),它只知道定義時其周圍范圍內的變數/狀態。結果,當您將間隔排隊時:
setInterval(handleNext, slideDuration)
您將執行handleNext只知道當時組件狀態的函式。當您的組件最終重新渲染并為 設定新值時activeIndex,您的時間間隔仍將handleNext執行先前渲染中定義的“舊”函式,該函式不知道新更新的狀態。解決此問題的一種選擇是使hanldeNext函式不依賴從其外部范圍獲得的狀態,而是使用狀態設定器函式來獲取當前值:
const handleNext = () => {
setActiveIndex(currIndex => (currIndex 1) % 4);
};
上面我習慣%將索引回圈回0,但你也可以使用你的 if 陳述句,如果你在哪里return 0,currIndex >= 3或者return currIndex 1在你的else.
我還建議您洗掉slideTimer. 這個狀態值沒有被用來描述你的 UI(你可以看到你沒有slideTimer在回傳的 JSX 中使用)。在這種情況下,您最好使用 ref 來存盤間隔 id:
const slideTimerRef = useRef(0); // instead of the `slideTimer` state
...
clearInterval(slideTimerRef.current);
slideTimerRef.current = null;
...
slideTimerRef.current = setInterval(handleNext, slideDuration);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/517868.html
