Created
September 6, 2017 16:01
-
-
Save jaredpalmer/ef2723b81c4322ca58bb9ccc5bc48446 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
class ReducerComponent<Props, State> extends React.Component<Props, State> { | |
constructor(props: Props) { | |
super(props); | |
} | |
reducer = (state: State, action: string) => { | |
// this should be | |
return state; | |
}; | |
reduce = (action: string) => { | |
this.setState((prevState, prevProps) => this.reducer(prevState, action)); | |
}; | |
} | |
interface CounterState { | |
count: number; | |
} | |
export class Counter extends ReducerComponent<{}, CounterState> { | |
state = { | |
count: 0, | |
}; | |
reducer = (state: CounterState, action: string) => { | |
switch (action) { | |
case 'increment': | |
return { ...state, count: state.count++ }; | |
case 'decrement': | |
return { ...state, count: state.count-- }; | |
case 'reset': | |
return { ...state, count: 0 }; | |
default: | |
return state; | |
} | |
}; | |
render() { | |
return ( | |
<div> | |
Count: {this.state.count} | |
<button onClick={() => this.reduce('increment')}>-</button> | |
<button onClick={() => this.reduce('decrement')}>+</button> | |
<button onClick={() => this.reduce('reset')}>Reset</button> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment