|
1 |
| -import { useState, useEffect, useRef } from 'react'; |
| 1 | +import { Component } from 'react'; |
2 | 2 | import PropTypes from 'prop-types';
|
3 | 3 |
|
4 |
| -const ReactTimer = ({ |
5 |
| - children, |
6 |
| - start = 0, |
7 |
| - end = () => true, |
8 |
| - interval = 1000, |
9 |
| - onEnd = () => { }, |
10 |
| - onTick = () => { }, |
11 |
| -}) => { |
12 |
| - const [value, setValue] = useState(start); |
13 |
| - const timerRef = useRef(); |
| 4 | +class ReactTimer extends Component { |
| 5 | + constructor(props) { |
| 6 | + super(props); |
| 7 | + this.state = { |
| 8 | + value: props.start || 0, |
| 9 | + }; |
| 10 | + this.timer = null; |
| 11 | + } |
14 | 12 |
|
15 |
| - useEffect(() => { |
16 |
| - if (!timerRef.current) { |
17 |
| - timerRef.current = setInterval(() => { |
18 |
| - setValue((val) => onTick(val)); |
19 |
| - }, interval); |
20 |
| - } |
21 |
| - if (end(value)) { |
22 |
| - clearInterval(timerRef.current); |
23 |
| - onEnd(value); |
| 13 | + componentDidMount() { |
| 14 | + const { |
| 15 | + onTick, |
| 16 | + interval, |
| 17 | + end, |
| 18 | + onEnd, |
| 19 | + } = this.props; |
| 20 | + this.timer = setInterval(() => { |
| 21 | + this.setState(({ value }) => ( |
| 22 | + { value: onTick(value) } |
| 23 | + ), () => { |
| 24 | + const { value: currentValue } = this.state; |
| 25 | + if (end(currentValue)) { |
| 26 | + clearInterval(this.timer); |
| 27 | + onEnd(currentValue); |
| 28 | + } |
| 29 | + }); |
| 30 | + }, interval); |
| 31 | + } |
| 32 | + |
| 33 | + componentWillUnmount() { |
| 34 | + if (this.timer) { |
| 35 | + clearInterval(this.timer); |
24 | 36 | }
|
25 |
| - }, [end, interval, onEnd, onTick, value]); |
| 37 | + } |
26 | 38 |
|
27 |
| - useEffect(() => () => { |
28 |
| - clearInterval(timerRef.current); |
29 |
| - }, []); |
| 39 | + render() { |
| 40 | + const { children } = this.props; |
| 41 | + const { value } = this.state; |
| 42 | + return children(value); |
| 43 | + } |
| 44 | +} |
30 | 45 |
|
31 |
| - return children(value); |
| 46 | +ReactTimer.defaultProps = { |
| 47 | + interval: 1000, |
| 48 | + onEnd: () => { }, |
| 49 | + onTick: () => { }, |
32 | 50 | };
|
33 | 51 |
|
34 | 52 | ReactTimer.propTypes = {
|
|
0 commit comments