【发布时间】:2022-01-14 00:19:25
【问题描述】:
我想用 useState、useEffect 和 setInterval 制作时钟。但是当我运行这段代码时,每秒都会记录一次“hello”。在实际代码中,另一个代码已经到位,而不是我真的只想执行一次的“hello”。我怎么解决这个问题? (使用 useEffect 不是必需的。)
const [clock, setClock] = useState({ year: "", month: "", date: "", hours: "", minutes: "" });
console.log("hello")
useEffect(() => {
const updateEverySecond = setInterval(() => {
setClock(getClock());
}, 1000);
return () => {
clearInterval(updateEverySecond);
};
}, []);
另外,这是getClock()的代码。
function getClock() {
let now = new Date();
var monthArray = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
const year = String(now.getFullYear());
const month = String(monthArray[now.getMonth()]);
const date = String(now.getDate());
const hours = String(now.getHours());
const minutes = String(now.getMinutes()).padStart(2, 0);
return { year, month, date, hours, minutes };
};
【问题讨论】: