Last active
March 30, 2017 20:36
-
-
Save conorhastings/b00a2347cb97a65c5cd99f30c6b69bf7 to your computer and use it in GitHub Desktop.
you can enact most of the behavior of redux with a simple component
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
/* this lacks subscribe behavior or ability to dispatch from outside of component tree but that is generally not neccesary */ | |
class State extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = YOUR_INITIAL_STATE; | |
} | |
reducer = (action, state, props) => {...newState}; | |
/* setState takes an object of new state as first arg or a function of props and state that returns new state | |
* which we will use here | |
* we pass dispatch around and use it similarly to redux dispatch | |
*/ | |
dispatch = action => this.setState(reducer.bind(null, action)); | |
render() { | |
return <App {...this.state} {...this.props} dispatch={this.dispatch} />; | |
} | |
} |
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
/* we can also use a HOC to maintain state for a specific subtree */ | |
function stateHOC(Component, initState, reducer) { | |
return class State extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = initState; | |
} | |
dispatch = action => this.setState(reducer.bind(this, action)); | |
render() { | |
return <Component {...this.state} {...this.props} dispatch={this.dispatch} />; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where the
newState
comes from? also for return {} I think it needs to ({})