Skip to content

Instantly share code, notes, and snippets.

@wolverineks
Last active August 12, 2018 18:14
Show Gist options
  • Save wolverineks/26d07935b21ac98600e6d18c11ee8a75 to your computer and use it in GitHub Desktop.
Save wolverineks/26d07935b21ac98600e6d18c11ee8a75 to your computer and use it in GitHub Desktop.
Connection Component
// Redux:
const INCREMENT = 'INCREMENT'
const increment = () => ({ type: INCREMENT })
const DECREMENT = 'DECREMENT';
const decrement = () => ({ type: DECREMENT })
const count = (state = 0, action) => {
switch (action.type) {
case INCREMENT: {
return state + 1
}
case DECREMENT: {
return state - 1
}
default:
return state
}
}
const store = Redux.createStore(count)
// React:
class Count extends React.Component {
render () {
const { count, increment, decrement } = this.props
return (
<div>
COUNT: {count}
<div>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
</div>
)
}
}
// React-Redux
const Provider = ReactRedux.Provider
const connect = ReactRedux.connect
const MSTP = state => ({ count: state })
const MDTP = dispatch => ({
increment: () => dispatch(increment()),
decrement: () => dispatch(decrement())
})
const RenderImplicit = ({ children, ...props }) => {
return React.Children.map(children, child => {
return React.cloneElement(child, props)
})
}
const RenderExplicit = ({ children, ...props }) => children(props)
const DEFAULTS = {
mapStateToProps: state => state,
mapDispatchToProps: dispatch => ({ dispatch }),
mergeProps: (stateProps, dispatchProps, ownProps) => ({
...ownProps,
...stateProps,
...dispatchProps
})
}
const Connection = connect(
(state, { mapStateToProps = DEFAULTS.mapStateToProps }) =>
mapStateToProps(state),
(dispatch, { mapDispatchToProps = DEFAULTS.mapDispatchToProps }) =>
mapDispatchToProps(dispatch),
(stateProps, dispatchProps, { mergeProps = DEFAULTS.mergeProps, ...ownProps }) =>
mergeProps(stateProps, dispatchProps, ownProps)
)
const ConnectionImplicit = Connection(RenderImplicit)
const ConnectionExplicit = Connection(RenderExplicit)
class App extends React.Component {
render () {
return (
<Provider store={store}>
<div>
<ConnectionImplicit mapStateToProps={MSTP} mapDispatchToProps={MDTP}>
<Count />
</ConnectionImplicit>
<ConnectionExplicit mapStateToProps={MSTP} mapDispatchToProps={MDTP}>{props =>
<Count {...props} />
}</ConnectionExplicit>
</div>
</Provider>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment