1
1
import React from 'react'
2
- import { connect , Provider } from 'react-redux'
3
- import { Dispatch } from 'redux'
2
+ import { useDispatch , useSelector , Provider } from 'react-redux'
4
3
import { createStore } from 'redux'
5
4
import styled from 'styled-components'
6
5
@@ -14,6 +13,7 @@ const reset = (num: number) => ({
14
13
type : RESET ,
15
14
payload : num ,
16
15
} )
16
+
17
17
type Action = ReturnType < typeof increment | typeof reset >
18
18
19
19
// Reducer
@@ -22,6 +22,7 @@ const initialCounterState = {
22
22
count : 0 ,
23
23
defaultCount : 0 ,
24
24
}
25
+
25
26
export const reducer = ( state = initialCounterState , action : Action ) => {
26
27
switch ( action . type ) {
27
28
case INCREMENT : {
@@ -40,16 +41,16 @@ export const reducer = (state = initialCounterState, action: Action) => {
40
41
// Store
41
42
export const store = createStore (
42
43
reducer ,
43
- ( window as any ) . __REDUX_DEVTOOLS_EXTENSION__ &&
44
- ( window as any ) . __REDUX_DEVTOOLS_EXTENSION__ ( )
44
+ ( window as any ) . __REDUX_DEVTOOLS_EXTENSION__ && ( window as any ) . __REDUX_DEVTOOLS_EXTENSION__ ( )
45
45
)
46
46
47
47
// Component
48
48
type Props = CounterState & {
49
49
increment : ( ) => Action
50
50
reset : ( num : number ) => Action
51
51
}
52
- const Component = ( props : Props ) => {
52
+
53
+ const Counter = ( props : Props ) => {
53
54
return (
54
55
< React . Fragment >
55
56
< Layout >
@@ -62,26 +63,29 @@ const Component = (props: Props) => {
62
63
</ React . Fragment >
63
64
)
64
65
}
66
+
65
67
const Layout = styled . div `
66
68
display: flex;
67
69
justify-content: center;
68
70
margin: 10px;
69
71
`
70
72
71
73
// Container
72
- const mapStateToProps = ( state : CounterState ) => state
73
- const mapDispatchToProps = ( dispatch : Dispatch ) => ( {
74
- increment : ( ) => dispatch ( increment ( ) ) ,
75
- reset : ( num : number ) => dispatch ( reset ( num ) ) ,
76
- } )
77
- const AppComponent = connect (
78
- mapStateToProps ,
79
- mapDispatchToProps
80
- ) ( Component )
74
+ const counterSelector = ( state : CounterState ) => state
75
+
76
+ const CounterContainer = ( ) => {
77
+ const { count } = useSelector ( counterSelector )
78
+ const dispatch = useDispatch ( )
79
+
80
+ const inc = ( ) => dispatch ( increment ( ) )
81
+ const res = ( num : number ) => dispatch ( reset ( num ) )
82
+
83
+ return < Counter defaultCount = { 0 } count = { count } increment = { inc } reset = { res } />
84
+ }
81
85
82
86
// connect Store
83
87
export const App = ( ) => (
84
88
< Provider store = { store } >
85
- < AppComponent />
89
+ < CounterContainer />
86
90
</ Provider >
87
91
)
0 commit comments