javascript - 具有明确和更新时间的自定义 Hook 无法按预期工作

标签 javascript reactjs react-hooks

使用 setInterval 更新默认时间时,它无法按预期工作。相反,它会作为新实例添加。如何清除自定义钩子(Hook)中的setInterval并更新新值?

app.jsx

import React from 'react';
import './style.css';
import CustomTimer from './Custom';
import { useState, useEffect } from 'react';

export default function App() {
  const [intervalTime, setIntervalTime] = useState(200);

  const time = CustomTimer(intervalTime);

  useEffect(() => {
    setTimeout(() => {
      console.log('Hi');
      setIntervalTime(500);
    }, 5000);
  });

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some happen! {time} </h2>
    </div>
  );
}

自定义.js

import { useEffect, useState } from 'react';

function CustomTimer(startTime) {
  const [timer, setTimer] = useState(startTime);
  useEffect(() => {
    const myInterval = setInterval(() => {
      if (timer > 0) {
        setTimer(timer - 1);
        console.log(timer);
      }
    }, 1000);
    return () => clearInterval(myInterval);
  }, [startTime]);
  return timer;
}

export default CustomTimer;

Live Demo =>请检查控制台

最佳答案

结果也可以在这里测试==> Test Demo

首先,需要在App.js文件中添加对useEffect的依赖,因为每当它触发时,计时器就会从头开始计时。

App.js:

import React from 'react';
import './style.css';
import CustomTimer from './Custom';
import { useState, useEffect } from 'react';

export default function App() {
  const [intervalTime, setIntervalTime] = useState(200);
  const time = CustomTimer(intervalTime);

  useEffect(() => {
    setTimeout(() => {
      setIntervalTime(500);
    }, 5000);
  }, []);  // Added dependency array here

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some happen! {time} </h2>
    </div>
  );
}

Custom.js:(添加注释行以解释添加/更新的行)

import { useEffect, useState } from 'react';

function CustomTimer(startTime) {
  const [timer, setTimer] = useState(startTime);

  useEffect(() => {
    setTimer(startTime);
    let timerCounter = startTime;

    const myInterval = setInterval(() => {
      if (timerCounter > 0) {
        // Get the previous state and decrease it 
        setTimer(timer => timer - 1);
        timerCounter--;
        return;
      }

      // Clear interval after timer's work is done
      clearInterval(myInterval);
    }, 1000);

    return () => clearInterval(myInterval);
  }, [startTime]);

  return timer;
}

export default CustomTimer;

关于javascript - 具有明确和更新时间的自定义 Hook 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77499074/

相关文章:

javascript - getAttribute() 返回空值?

javascript - 在 ES6 中导入用于服务端渲染的组件

javascript - 复制 $scope 持有的数据

javascript - 如何在 react 中保存多个复选框值

javascript - 使用 "nested"获取设置钩子(Hook)时,React、Axios、PokeAPI 返回未定义

javascript - es6 Javascript 类在回调中使用 this

javascript - 按字段值宽度获取和过滤数组中的图像

javascript - state中如何使用setState拼接成数组?

javascript - 如何使 react 倒数计时器

javascript - 是否可以通过 react (钩子(Hook))在另一个上下文中使用上下文?