setInterval in a React app

前端 未结 7 522
天涯浪人
天涯浪人 2020-11-30 20:46

I\'m still fairly new at React, but I\'ve been grinding along slowly and I\'ve encountered something I\'m stuck on.

I am trying to build a \"timer\" component in Re

相关标签:
7条回答
  • 2020-11-30 21:23

    Updated 10-second countdown using Hooks (a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha).

    import React, { useState, useEffect } from 'react';
    import ReactDOM from 'react-dom';
    
    const Clock = () => {
        const [currentCount, setCount] = useState(10);
        const timer = () => setCount(currentCount - 1);
    
        useEffect(
            () => {
                if (currentCount <= 0) {
                    return;
                }
                const id = setInterval(timer, 1000);
                return () => clearInterval(id);
            },
            [currentCount]
        );
    
        return <div>{currentCount}</div>;
    };
    
    const App = () => <Clock />;
    
    ReactDOM.render(<App />, document.getElementById('root'));
    
    0 讨论(0)
提交回复
热议问题