需求:实现一个定时器计数器,每秒自动+1
import React, { useState, useEffect } from "react";
export default function App() {
let [count, setCount] = useState(0);
useEffect(() => {
let timer = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return <div>{count}</div>;
}
以上写法有一个问题,页面会永远停留在数字1,并不会发生变化
正确的写法如下
import React, { useState, useEffect } from "react";
export default function App() {
let [count, setCount] = useState(0);
useEffect(() => {
let timer = setInterval(() => {
setCount((preValue) => {
return preValue + 1;
});
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return <div>{count}</div>;
}
方法签名
setCount(value)
setCount(preValue=>newValue)