Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

javascript - window.setInterval causing issues with timer component in React

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...