Reactjs -如何通过使用钩子使用效果和setInterval每秒添加一个项目到数组


/**
* init array: [1, 2]
* Expect
* array per 1s: [1, 2, 3]
* array per 2s: [1, 2, 3, 4]
* array per (n)s: [1, 2, 3, 4, ..., n]
*/
const [countList, setCountList] = useState([]);
const counter = useRef(0);
useEffect(() => {
const interval = setInterval(() => {
counter.current = counter.current + 1;
setCountList([...countList, counter.current]);
}, 1000);
return () => clearInterval(interval);
});
return (
<>
<div>{countList.map((count) => count + ',')}</div>
</>
);

我想每秒钟,数组push 1项,然后在UI上显示,但数组只更新最后一项。Exp [1,2] =>[1,3] =>[1,4]…

正确的方法是在挂载时只设置一次间隔,而不是反复设置和清除它。有点违背了设定间隔的目的。您需要使用回调函数来获取前一个值,并将一个空的依赖数组传递给useEffect

useEffect(() => {
const interval = setInterval(() => {
counter.current = counter.current + 1;
setCountList((prev) => [...prev, counter.current]);
}, 1000);
return () => clearInterval(interval);
}, []);

演示:https://stackblitz.com/edit/react-ts-1rt29v?file=App.tsx

试试这个

countList更新时,您必须重新生成interval

const [countList, setCountList] = React.useState([]);
const counter = React.useRef(0);
React.useEffect(() => {
const interval = setInterval(() => {
counter.current = counter.current + 1;
setCountList([...countList, counter.current]);
}, 1000);
return () => clearInterval(interval);
}, [countList]);

最新更新