11import * as React from 'react' ;
22
3- // Propsの型定義(今回は不要だが明示)
4- type CounterProps = { } ;
3+ // Redux 関連のインポート
4+ import { useSelector , useDispatch } from 'react-redux' ;
5+ import type { RootState , AppDispatch } from '../store' ;
6+ import { increment , reset } from '../store/counterSlice' ;
7+
8+ // --- 既存コード
9+
10+ // Propsの型定義
11+ type CounterProps //= {};
12+ = {
13+ currentCount : number ;
14+ onIncrement : ( ) => void ;
15+ onReset : ( ) => void ;
16+ } ;
517
618// Stateの型定義
719type CounterState = {
820 currentCount : number ;
921} ;
1022
11- export class Counter extends React . Component < CounterProps , CounterState > {
12- constructor ( props : CounterProps ) { // ← props を受け取るよう修正
13- super ( props ) ; // ← super(props) に修正
23+ // 以下、Redux修正あり
24+ // クラス名称を変更
25+ export class Counter_org extends React . Component < CounterProps , CounterState > {
26+ constructor ( props : CounterProps ) {
27+ super ( props ) ;
1428 this . state = { currentCount : 0 } ;
1529 }
1630
31+ // Reduxのdispatchを呼び出す形に変更
1732 render ( ) {
1833 return (
1934 < div >
2035 < h1 > Counter</ h1 >
2136 < p > This is a simple example of a React component.</ p >
22- < p > Current count: < strong > { this . state . currentCount } </ strong > </ p >
23- < button className = 'btn-primary' onClick = { ( ) => this . incrementCounter ( ) } >
37+ < p > Current count: < strong > { this . props . currentCount } </ strong > </ p >
38+ < button className = 'btn-primary' onClick = { ( ) => this . props . onIncrement ( ) } >
2439 Increment
2540 </ button >
41+ < button className = 'btn-primary' onClick = { ( ) => this . props . onReset ( ) } >
42+ Reset
43+ </ button >
2644 </ div >
2745 ) ;
2846 }
2947
30- incrementCounter ( ) {
48+ /* incrementCounter() {
3149 this.setState({
3250 currentCount: this.state.currentCount + 1,
3351 });
34- }
52+ }*/
3553}
54+
55+ // --- Reduxラッパー ---
56+ export const Counter = ( ) => {
57+ const currentCount = useSelector ( ( state : RootState ) => state . counter . value ) ;
58+ const dispatch = useDispatch < AppDispatch > ( ) ;
59+
60+ // dispatch の戻り値を void に吸収させる
61+ const handleIncrement = ( ) : void => { dispatch ( increment ( ) ) ; } ;
62+ const handleReset = ( ) : void => { dispatch ( reset ( ) ) ; } ;
63+
64+ return (
65+ < Counter_org
66+ currentCount = { currentCount }
67+ onIncrement = { handleIncrement }
68+ onReset = { handleReset }
69+ />
70+ ) ;
71+ } ;
0 commit comments