File tree Expand file tree Collapse file tree 3 files changed +44
-2
lines changed
2024 Prep/machine_coding/react/src Expand file tree Collapse file tree 3 files changed +44
-2
lines changed Original file line number Diff line number Diff line change 1
1
import './App.css'
2
- import { InputHookComp } from './components'
2
+ import { CounterWithReducer } from './components'
3
3
4
4
function App ( ) {
5
5
return (
6
6
< div className = "container" >
7
7
< h1 > Vite + React</ h1 >
8
- < InputHookComp />
8
+ < CounterWithReducer />
9
9
</ div >
10
10
)
11
11
}
Original file line number Diff line number Diff line change
1
+ import { useReducer } from 'react'
2
+
3
+ export default function CounterWithReducer ( ) {
4
+ const counterReducer = ( state , action : { type : string } ) => {
5
+ switch ( action . type ) {
6
+ case 'increment' : {
7
+ return { count : state . count + 1 }
8
+ }
9
+
10
+ case 'decrement' : {
11
+ return { count : state . count - 1 }
12
+ }
13
+ default :
14
+ return
15
+ }
16
+ }
17
+ const initialState = {
18
+ count : 0 ,
19
+ }
20
+ const [ state , dispatch ] = useReducer ( counterReducer , initialState )
21
+
22
+ const onUpdateCounter = ( type : string ) => {
23
+ dispatch ( { type } )
24
+ }
25
+
26
+ return (
27
+ < div
28
+ style = { {
29
+ display : 'grid' ,
30
+ placeContent : 'center' ,
31
+ } }
32
+ >
33
+ < h2 > Counter With Reducer</ h2 >
34
+ < h4 > counter: { state ?. count } </ h4 >
35
+
36
+ < button onClick = { ( ) => onUpdateCounter ( 'increment' ) } > Increment +</ button >
37
+ < button onClick = { ( ) => onUpdateCounter ( 'decrement' ) } > Decrement -</ button >
38
+ </ div >
39
+ )
40
+ }
Original file line number Diff line number Diff line change @@ -5,6 +5,7 @@ import BatchingStates from './BatchingStates'
5
5
import CountDownTimer from './Timer'
6
6
import LiftingUpState from './LiftingStateUp'
7
7
import InputHookComp from './InputCustomHookComp'
8
+ import CounterWithReducer from './CounterWithReducer'
8
9
9
10
export {
10
11
Loader ,
@@ -14,4 +15,5 @@ export {
14
15
CountDownTimer ,
15
16
LiftingUpState ,
16
17
InputHookComp ,
18
+ CounterWithReducer ,
17
19
}
You can’t perform that action at this time.
0 commit comments