Last active
October 22, 2018 23:22
-
-
Save ryanflorence/51ed3c09be94efb7786a2fe3855ba7c0 to your computer and use it in GitHub Desktop.
Sweatpants
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" | |
import ReactDOM from 'react-dom' | |
let reducer = (state={count: 0}, action) => { | |
if (action.type === 'up') { | |
return { | |
...state, | |
count: state.count + 1 | |
} | |
} else { | |
return state | |
} | |
} | |
ReactDOM.render(( | |
<StateProvider reducer={reducer}> | |
<App/> | |
</StateProvider> | |
), node) | |
///////////////////////////////// | |
let SomeScreen = () => ( | |
<State> | |
{({ state, dispatch }) => ( | |
<div> | |
<h1>{state.count}</h1> | |
<button onClick={() => dispatch({ type: 'up' })}>Up</button> | |
</div> | |
)} | |
</State> | |
) |
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" | |
let Context = React.createContext() | |
class StateProvider extends React.Component { | |
state = { | |
state: this.props.reducer(undefined, '@@INIT'), | |
dispatch: (action) => { | |
this.setState(state => ({ state: this.props.reducer(state, action)})) | |
} | |
} | |
render() { | |
let { reducer, ...props } = this.props | |
return ( | |
<Context.Provider value={this.state} {...props}/> | |
) | |
} | |
} | |
let State = Context.Consumer | |
export { StateProvider, State } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment