-
-
Save itrelease/37e1ca1683f49387609d 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, { Component } from 'react'; | |
// Usage: | |
// | |
// @Stateful({ | |
// initialize(props) { | |
// return { | |
// count: 0 | |
// }; | |
// }, | |
// reducers: { | |
// increment(props, state) { | |
// return { | |
// count: state.count + 1 | |
// }; | |
// } | |
// } | |
// }) | |
// class Counter { | |
// static propTypes = { | |
// count: PropTypes.number.isRequired, | |
// increment: PropTypes.func.isRequired | |
// }; | |
// render() { | |
// const { count, increment } = this.props; | |
// return ( | |
// <button onClick={increment}> | |
// Pressed {count} times. | |
// </button> | |
// ) | |
// } | |
// } | |
export default function Stateful({ initialize, reducers }) { | |
return DecoratedComponent => class StateContainer extends Component { | |
constructor(props) { | |
super(props); | |
this.state = initialize(props); | |
this.reducers = {}; | |
Object.keys(reducers).forEach(key => { | |
this.reducers[key] = (...args) => { | |
const nextState = reducers[key](this.props, this.state, ...args); | |
this.setState(nextState); | |
} | |
}); | |
} | |
render() { | |
return <DecoratedComponent {...this.props} | |
{...this.state} | |
{...this.reducers} />; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment