将功能组件代码转换为类组件代码

时间:2021-07-05 11:00:17

标签: javascript reactjs use-effect react-functional-component react-class-based-component

我是 React 中函数式组件的新手,想知道如何将下面的代码从基于函数的代码转换为基于类的代码。我试过了,但在“React.useEffect”方面遇到了麻烦。

任何帮助将不胜感激! :)

(另外一个问题,你会说我学习函数式组件比基于类更好吗?)

代码

import { Component } from "react";
import "./App.css";
import React from "react";
import audio from "./250629__kwahmah-02__alarm1.mp3";
import UIfx from "uifx";
import { render } from "@testing-library/react";

function Timer() {
  const [time, setTime] = React.useState(0);
  const [timerOn, setTimeOn] = React.useState(false);

  React.useEffect(() => {
    let interval = null;
    if (timerOn) {
      interval = setInterval(() => {
        setTime((prevTime) => prevTime + 1); // We wanna increase the time every 10 milliseconds
      }, 1000);
    } else {
      clearInterval(interval);
    }

    return () => clearInterval(interval);
  }, [timerOn]);

  return (
    <div className="App">
      <header className="App-header">
        {/* <div>{time}</div> */}
        <div>
          <h1>
            {("0" + parseInt(time / 3600)).slice(-2)}:
            {("0" + parseInt((time / 60) % 60)).slice(-2)}:
            {("0" + parseInt(time % 60)).slice(-2)}
          </h1>
        </div>
        <div>
          {!timerOn && time === 0 && (
            <button id="StartTimer" onClick={() => setTimeOn(true)}>
              Start
            </button>
          )}
          {timerOn && (
            <button id="PauseTimer" onClick={() => setTimeOn(false)}>
              Pause
            </button>
          )}
          {!timerOn && time !== 0 && (
            <button id="ResumeTimer" onClick={() => setTimeOn(true)}>
              Resume
            </button>
          )}
          {!timerOn && time > 0 && (
            <button id="ResetTimer" onClick={() => setTime(0)}>
              Reset
            </button>
          )}
        </div>
      </header>
    </div>
  );
}

export default Timer;

1 个答案:

答案 0 :(得分:1)

类组件中的副作用由 componentDidMountcomponentDidUpdate 处理

所以你的 useEffect 钩子会变成这样:

componentDidUpdate() {
    let interval = null;
    if (timerOn) {
      interval = setInterval(() => {
        setTime((prevTime) => prevTime + 1); // We wanna increase the time every 10 milliseconds
      }, 1000);
    } else {
       clearInterval(interval);
    }
}

请记住,现在必须在 clearInterval(interval) 生命周期方法中进行任何像 componentWillUnmount 这样的清理

但建议使用功能组件。

相关问题