回答編集履歴
1
追記
test
CHANGED
@@ -57,3 +57,67 @@
|
|
57
57
|
};
|
58
58
|
|
59
59
|
```
|
60
|
+
|
61
|
+
|
62
|
+
|
63
|
+
---
|
64
|
+
|
65
|
+
|
66
|
+
|
67
|
+
追記。MyTimer のアンマウント時にタイマーを止めることを考えると useEffect を使うべきでしょうね。
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
```js
|
72
|
+
|
73
|
+
const MyTimer = () => {
|
74
|
+
|
75
|
+
const [count, setCount] = useState(0);
|
76
|
+
|
77
|
+
const [timer, setTimer] = useState(false);
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
const countup = () => {
|
82
|
+
|
83
|
+
setCount(count => count + 1);
|
84
|
+
|
85
|
+
};
|
86
|
+
|
87
|
+
|
88
|
+
|
89
|
+
useEffect(() => {
|
90
|
+
|
91
|
+
if (timer) {
|
92
|
+
|
93
|
+
const timerId = setInterval(countup, 1000);
|
94
|
+
|
95
|
+
return () => clearInterval(timerId);
|
96
|
+
|
97
|
+
}
|
98
|
+
|
99
|
+
}, [timer]);
|
100
|
+
|
101
|
+
|
102
|
+
|
103
|
+
return (
|
104
|
+
|
105
|
+
<div>
|
106
|
+
|
107
|
+
<h2>My Timer</h2>
|
108
|
+
|
109
|
+
<div>{String(count)}</div>
|
110
|
+
|
111
|
+
<button onClick={() => setTimer(true)}>スタート</button>
|
112
|
+
|
113
|
+
<button onClick={() => setTimer(false)}>ストップ</button>
|
114
|
+
|
115
|
+
<button onClick={() => setCount(0)}>リセット</button>
|
116
|
+
|
117
|
+
</div>
|
118
|
+
|
119
|
+
);
|
120
|
+
|
121
|
+
};
|
122
|
+
|
123
|
+
```
|