使用 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/