【问题标题】:Why is this code render 0,2,3,0,1,2,3 etc为什么此代码呈现 0,2,3,0,1,2,3 等
【发布时间】:2023-01-19 00:23:18
【问题描述】:
const [index, setIndex] = useState(0);
useEffect(()=>{
if (index === 3){
setIndex(0)
console.log(index)
}else{
setTimeout(() => setIndex((index) => index + 1), 2000);
console.log(index)
}
}, [index]);
所以我的问题是为什么上面的这段代码第一次跳过 1?
console.log() 返回以下 0 0 2 3 0 1 2 3 0 现在在这里我理解 0 0 因为我注销了它然后 2 由于某种原因我没有得到它并且再次 3 0 1 2 是可以理解的
我想根据它在数组中的索引更改 DOM 中的名称
【问题讨论】:
标签:
reactjs
arrays
loops
react-hooks
【解决方案1】:
在发展由于 StrictMode,模式为 useEffect will run twice on mount。
所以 setTimeout 将运行两次,并且由于您没有提供 cleanup function 它将继续存在并继续设置状态。这导致状态设置两次,因此从 0 变为 2。
在生产StrictMode 被禁用,因此不会触发 useEffect 两次。
相反,你可以做这样的事情
useEffect(() => {
let timeoutId;
if (index === 3) {
setIndex(0);
console.log(index);
} else {
timeoutId = setTimeout(() => setIndex((index) => index + 1), 2000);
console.log(index);
}
return () => clearTimeout(timeoutId);
}, [index]);
但是,如果您尝试进行某种计数器/间隔,我建议使用setInterval。
useEffect(() => {
// set id to use in the cleanup
const timerId = setInterval(
() =>
// use inline check so we have access to the actual index
setIndex((prevIndex) => {
if (prevIndex === 3) return 0;
return prevIndex + 1;
}),
2000
);
return () => clearInterval(timerId);
}, []);