I am building a typeracer web app with React and I am currently working on the Header component, which contains a Countdown component, which counts down from 5, and a Timer component, which starts counting up when the countdown hits 0. This is my code:
Countdown:
export default function Countdown(props) {
return (
<div className="col-6" id="start">
<h3>{props.isTyping ? 'Start' : `0:0${props.time}`}</h3>
</div>
)
}
Timer:
function getTextForTime(seconds) {
const minutes = Math.floor(seconds / 60)
seconds %= 60
return `${minutes}:${seconds < 10 ? `0${seconds}` : seconds}`
}
export default function Timer(props) {
return (
<div className="col-6" id="timer">
<h3>{getTextForTime(props.time)}</h3>
</div>
)
}
Header (imports Countdown and Timer):
export default function Header(props) {
console.log('new render')
const [isTyping, setIsTyping] = useState(false)
const [countdown, setCountdown] = useState(5)
const [time, setTime] = useState(0)
window.setInterval(() => {
if (countdown == 0) {
if (!isTyping) setIsTyping(true)
setTime(time + 1)
console.log(time)
} else {
setCountdown(countdown - 1)
}
}, 1000)
return (
<div className="jumbotron-fluid bg-dark text-center text-light p-3">
<div className="row">
<Countdown isTyping={isTyping} time={countdown}/>
<Timer time={time}/>
</div>
</div>
)
}
The Header component seems to re-render an increasing number of times during each interval, which causes the Timer component to not behave as expected. How do I fix this?
question from:
https://stackoverflow.com/questions/66056173/window-setinterval-causing-issues-with-timer-component-in-react 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…