Created
July 28, 2015 07:12
-
-
Save threepointone/8a1dce2ae36618571587 to your computer and use it in GitHub Desktop.
a lightweight flux style store as a component
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 React from 'react'; | |
export class Sto extends React.Component{ | |
static defaultProps = { | |
store: x => x | |
} | |
state = { | |
value: this.props.store() | |
} | |
dispatch = action => this.setState({ | |
value: this.props.store(this.state.value, action) | |
}) | |
render(){ | |
return this.props.children(this.state.value, this.dispatch); | |
} | |
} | |
function store(counter = 0, action){ | |
switch(action.type){ | |
case 'inc': return counter + 1; | |
case 'dec': return counter - 1; | |
default: return counter; | |
} | |
} | |
export class App{ | |
render(){ | |
return <Sto store={store}>{ | |
(state, dispatch) => <div onClick={() => dispatch({type: 'inc'})}> | |
clicked {state} times | |
</div> | |
}</Sto>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment