这个是官方的一个例子,我改了一下,能够正常计数,从 100 开始倒数。
请问,如何在 count === 0 的时候,停止刷新 /计数?
import React, { useState, useEffect } from "react";
export default function Counter() {
const [count, setCount] = useState(100);
useEffect(() => {
const id = setInterval(() => {
setCount((c) => c - 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}
1
dxhuii 2020-11-05 22:55:10 +08:00
试试这样
```js import React, { useState, useEffect } from "react"; export default function Counter() { const [count, setCount] = useState(10); useEffect(() => { const id = setInterval(() => { setCount((c) => c - 1); }, 1000); if (count === 0) { clearInterval(id); console.log("执行到了这里"); } return () => clearInterval(id); }, [count]); return <h1>{count}</h1>; } ``` |
2
syfless 2020-11-05 23:07:05 +08:00
把那行 setCount 换成这个就行
```js ``` |
3
syfless 2020-11-05 23:07:30 +08:00
把那行 setCount 换成这个就行
```js setCount((c) => { if (c > 5) { return c - 1; } clearInterval(id); return c; }); ``` |
4
yihouzenmeban 2020-11-06 00:00:00 +08:00
|
5
funnyecho 2020-11-06 10:51:20 +08:00
不用 setInterval,用 setTimeout + useEffect 就好
useEffect(() => { if (count <= 0) return const id = setTimeout(() => { setCount((c) => c - 1); }, 1000); return () => clearInterval(id); }, [count]); |
6
yazoox OP |
7
source 2021-01-06 15:00:50 +08:00
emmmm,难道不是在 setCount 这里加个判断就行了么?
|