跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • react useEffect 里面的计数器,如何在达到指定数字后,停止下来?
未分類
6 11 月 2020

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

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

資深大佬 : yazoox 2

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

大佬有話說 (6)

  • 資深大佬 : dxhuii

    试试这样

    “`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

    把那行 setCount 换成这个就行
    “`js
    “`

  • 資深大佬 : syfless

    把那行 setCount 换成这个就行
    “`js
    setCount((c) => {
    if (c > 5) {
    return c – 1;
    }
    clearInterval(id);
    return c;
    });
    “`

  • 資深大佬 : yihouzenmeban

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

  • 資深大佬 : funnyecho

    不用 setInterval,用 setTimeout + useEffect 就好

    useEffect(() => {
    if (count <= 0) return

    const id = setTimeout(() => {
    setCount((c) => c – 1);
    }, 1000);

    return () => clearInterval(id);
    }, [count]);

  • 主 資深大佬 : yazoox

    @funnyecho 这个可以工作

    @dxhuii 这个可能工作

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

    谢谢大家。

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具