|
1 |
| -import React, {useState} from 'react' |
| 1 | +import React, {useEffect, useState} from 'react' |
2 | 2 | import ReactDOM from 'react-dom'
|
3 | 3 |
|
4 | 4 |
|
5 |
| -const BtnLabel = (props) =>{ |
| 5 | +const Timer = (props) =>{ |
| 6 | + const [count, setCount] = useState(-1) |
| 7 | + console.log(count, props) |
| 8 | + useEffect(()=>{ |
| 9 | + // lookup to api service |
| 10 | + }, []) |
6 | 11 |
|
7 |
| - return <span> - {props.count} </span> |
8 |
| -} |
| 12 | + useEffect(()=>{ |
| 13 | + // console.log("mounted") |
| 14 | + // setCount(count+1) |
| 15 | + let myTimer; |
| 16 | + if (count > 10) { |
| 17 | + myTimer = setTimeout(()=>{ |
| 18 | + setCount(count + 1) |
| 19 | + }, 1000) |
| 20 | + } |
| 21 | + |
| 22 | + return () => { |
| 23 | + clearTimeout(myTimer) |
| 24 | + } |
| 25 | + }, [count]) |
9 | 26 |
|
10 |
| -const Btn = (props) =>{ |
11 |
| - const [clickCount, setClickCount] = useState(0) |
12 |
| - console.log(props) |
13 |
| - const shouldRenderCount = props.renderCount === true ? true : false |
14 |
| - const renderCountLabel = shouldRenderCount === true ? <BtnLabel count={clickCount} /> : null |
15 |
| - const handleClick = (event) =>{ |
16 |
| - // alert("btn in react") |
17 |
| - setClickCount(clickCount + 1) |
| 27 | + const handleClick = _ => { |
| 28 | + setCount(count + 1) |
18 | 29 | }
|
19 |
| - return <button onClick={handleClick} className={`class-${clickCount}`}>hello react btn {renderCountLabel}</button> |
| 30 | + |
| 31 | + return <div> |
| 32 | + |
| 33 | + <h1>Timer - {count}</h1> |
| 34 | + <button onClick={handleClick}>Reset</button> |
| 35 | + </div> |
20 | 36 | }
|
21 | 37 |
|
22 | 38 | const App = () => {
|
23 | 39 | return <div>Hello world again.
|
24 |
| - |
25 |
| - <p> <Btn renderCount /></p> |
26 |
| - <p> <Btn /></p> |
27 |
| - <p> <Btn /></p> |
28 |
| - <p> <Btn /></p> |
| 40 | + <Timer className='my-timer' /> |
29 | 41 | </div>
|
30 | 42 | }
|
31 | 43 |
|
|
0 commit comments