React UseEffect 挂钩问题渲染间隔
React UseEffect hook Issue Rendering an Interval
在下面的 React 组件中,我试图按每一秒添加增量计数,因此它看起来像一个秒表,但计数显示为 2,然后闪烁到 3,然后又回到 2。有没有人知道如何处理这个错误,并让计数按预期显示吗?
import React, { useEffect, useState } from "react";
const IntervalHook = () => {
const [count, setCount] = useState(0);
const tick = () => {
setCount(count + 1);
};
useEffect(() => {
const interval = setInterval(tick, 1000);
return () => {
clearInterval(interval);
};
}, [ count ]);
return <h1> {count} </h1>;
};
export default IntervalHook;
如果您想根据其先前的值更改某些状态,请使用函数:setCount(count => count + 1);
并且您的 useEffect
将独立于 [ count ]
。喜欢
useEffect(() => {
const tick = () => {
setCount(count => count + 1);
};
const interval = setInterval(tick, 1000);
return () => {
clearInterval(interval);
};
}, [setCount]);
或者你去掉tick()
然后写。
useEffect(() => {
const interval = setInterval(setCount, 1000, count => count + 1);
return () => {
clearInterval(interval);
};
}, [setCount]);
但我觉得使用减速器更干净:
const [count, increment] = useReducer(count => count + 1, 0);
useEffect(() => {
const interval = setInterval(increment, 1000);
return () => {
clearInterval(interval);
};
}, [increment]);
在下面的 React 组件中,我试图按每一秒添加增量计数,因此它看起来像一个秒表,但计数显示为 2,然后闪烁到 3,然后又回到 2。有没有人知道如何处理这个错误,并让计数按预期显示吗?
import React, { useEffect, useState } from "react";
const IntervalHook = () => {
const [count, setCount] = useState(0);
const tick = () => {
setCount(count + 1);
};
useEffect(() => {
const interval = setInterval(tick, 1000);
return () => {
clearInterval(interval);
};
}, [ count ]);
return <h1> {count} </h1>;
};
export default IntervalHook;
如果您想根据其先前的值更改某些状态,请使用函数:setCount(count => count + 1);
并且您的 useEffect
将独立于 [ count ]
。喜欢
useEffect(() => {
const tick = () => {
setCount(count => count + 1);
};
const interval = setInterval(tick, 1000);
return () => {
clearInterval(interval);
};
}, [setCount]);
或者你去掉tick()
然后写。
useEffect(() => {
const interval = setInterval(setCount, 1000, count => count + 1);
return () => {
clearInterval(interval);
};
}, [setCount]);
但我觉得使用减速器更干净:
const [count, increment] = useReducer(count => count + 1, 0);
useEffect(() => {
const interval = setInterval(increment, 1000);
return () => {
clearInterval(interval);
};
}, [increment]);