react useEffect 里面的计数器,如何在达到指定数字后,停止下来?

2020-11-05 22:35:05 +08:00
 yazoox

这个是官方的一个例子,我改了一下,能够正常计数,从 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>;
}

refer to: https://react.docschina.org/docs/hooks-faq.html#what-do-hooks-mean-for-popular-apis-like-redux-connect-and-react-router

2506 次点击
所在节点    React
7 条回复
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>;
}
```
syfless
2020-11-05 23:07:05 +08:00
把那行 setCount 换成这个就行
```js
```
syfless
2020-11-05 23:07:30 +08:00
把那行 setCount 换成这个就行
```js
setCount((c) => {
if (c > 5) {
return c - 1;
}
clearInterval(id);
return c;
});
```
yihouzenmeban
2020-11-06 00:00:00 +08:00
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]);
yazoox
2020-11-06 16:19:43 +08:00
@funnyecho 这个可以工作

@dxhuii 这个可能工作

@syfless 这个也可能工作。不过,最后当 c <= 5 时,没有返回值,这时,count 好像被设置成了 undefined 。UI 上原来显示数字倒计时的,最后就消失了。

谢谢大家。
source
2021-01-06 15:00:50 +08:00
emmmm,难道不是在 setCount 这里加个判断就行了么?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/722183

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX