极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
每天晚上九点 B站讲解前端工程化直播,并解答相关问题。

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

更多描述

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

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

Issue

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

Author

回答者: Hack-Jay (opens new window)

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>
        )
}
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 new window)

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>;
}

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

可使用 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>
  );
}
Last Updated: 11/27/2021, 10:11:48 AM