高级前端
react
【Q014】如何使用 react hooks 实现一个计数器的组件

如何使用 react hooks 实现一个计数器的组件

更多描述 如何使用 react hooks 实现最简单一个计数器的组件

为了保证最最简单化,不需要暂停与开始状态

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 15 (opens in a new tab)

Author 回答者: Hack-Jay (opens in a new tab)

import React, { useState, useEffect } from 'react'
import useCountDown from './useCountDown'

const useCountDown = (num) => {
    const [seconds, setSecond] = useState(num)

    useEffect(() => {
        setTimeout(() => {
            if (seconds > 0) {
                setSecond(c => c - 1);
            }
        }, 1000);
    }, [seconds]);

    return [seconds, setSecond]
}

// use it
const Demo = () => {
    const [seconds, setSecond] = useCountDown(0)
    return (
             <Button
                disable={seconds !== 0}
                onClick={() => setSecond(59)}
            >
                {seconds > 0 ? `${seconds}s后可点击` : '点击开始倒计时'}
            </Button>
        )
}

Author 回答者: bWhirring (opens in a new tab)

import React, { useEffect, useState } from "react";
 
function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    setInterval(() => {
      setCount((count) => count + 1);
    }, 1000);
  }, []);
 
  return <h1>{count}</h1>;
}

Author 回答者: shaul-xu (opens in a new tab)

import React, { useEffect, useState } from "react";
 
function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const timer = setInterval(() => {
      setCount((count) => count + 1);
    }, 1000);
 
    return () => {
      clearInterval(timer);
    };
  }, []);
 
  return <h1>{count}</h1>;
}

Author 回答者: shfshanyue (opens in a new tab)

代码见 如何使用 React Hooks 实现计数器组件 - codesandbox (opens in a new tab)

可使用 setTimeoutsetInterval 实现。

其中,使用 setTimeout 实现时,当页面处于不可见 (document.hidden = false) 状态时,将可能会停止计时,建议使用 setInterval 实现

import { useEffect, useState } from "react";
import "./styles.css";
 
function CounterWithTimeout() {
  const [count, setCount] = useState(0);
  useEffect(() =>
    setTimeout(() => {
      setCount(count + 1);
    }, 1000),
  );
  return <h1>{count}</h1>;
}
 
function CounterWithInterval() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const timer = setInterval(() => {
      setCount((count) => count + 1);
    }, 1000);
 
    return () => {
      clearInterval(timer);
    };
  }, []);
 
  return <h1>{count}</h1>;
}
 
export default function App() {
  return (
    <div>
      <CounterWithTimeout />
      <CounterWithInterval />
    </div>
  );
}

Author 回答者: Gumplefik (opens in a new tab)

这题不要想当然的就超时1s加或者减1,要记录开始时间戳,重新set时检查剩余多少秒,去set对应的值。 定时器都是指定时间后开始执行,不是指定时间执行