Created
September 6, 2017 15:59
-
-
Save jaredpalmer/205d8aa0244366e864200d31c1ad5214 to your computer and use it in GitHub Desktop.
This file contains 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 React from 'react'; | |
class ReducerComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
} | |
reducer = {}; | |
dispatch = action => | |
this.setState((state, props) => this.reducer[action](state, props)); | |
} | |
// this can be defined anywhere | |
const counter = { | |
increment: (state, props) => ({ ...state, count: state++ }), | |
decrement: (state, props) => ({ ...state, count: state.count-- }), | |
} | |
class Counter extends ReducerComponent { | |
state = { | |
count: 0, | |
}; | |
reducer = { | |
...counter, // nicer than combine reducer amirite? | |
reset: (state, props) => ({ ...state, count: 0 }), | |
}; | |
render() { | |
return ( | |
<div> | |
Counter: {this.state.count} | |
<button onClick={() => this.dispatch('increment')}>-</button> | |
<button onClick={() => this.dispatch('decrement')}>+</button> | |
<button onClick={() => this.dispatch('reset')}>Reset</button> | |
</div> | |
); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment