React hooks使用setInterval产生的问题

需求: 显示当前的最新时分秒

一看哇,着很简单啊,刷刷刷开始写代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React, { useEffect, useState } from "react";

export default function App() {
const [hour, setHour] = useState();
const [minute, setMinute] = useState();
const [second, setSecond] = useState();

useEffect(() => {
const intervalId = setInterval(() => {
const nowDate = new Date();
setHour(() => nowDate.getHours());
setMinute(() => nowDate.getMinutes());
setSecond(() => nowDate.getSeconds());
}, 1000);
return clearInterval(intervalId)
}, []);

return <h1>{hour}时{minute}分{second}秒</h1>;
}

一顿操作猛如虎,运行一看就咋回事跑成这个鬼样子呢?

怎么没正常显示呢

写一个useInterval的hooks,这样时间就正常显示了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import React, { useEffect, useState, useRef } from "react";

const useInterval = (callback, delay) => {
const savedCallback = useRef(() => {});

useEffect(() => {
savedCallback.current = callback;
});

useEffect(() => {
if (delay !== null) {
const interval = setInterval(() => savedCallback.current(), delay || 0);
return () => clearInterval(interval);
}

return undefined;
}, [delay]);
};

export default function App() {
const [hour, setHour] = useState();
const [minute, setMinute] = useState();
const [second, setSecond] = useState();

useInterval(() => {
const nowDate = new Date();
setHour(nowDate.getHours());
setMinute(nowDate.getMinutes());
setSecond(nowDate.getSeconds());
}, 1000);

return <h1>{hour}时{minute}分{second}秒</h1>;
}

如下

为啥直接在useEffect里写就没用呢,你猜猜?