Revisions
-
gaearon created this gist
Apr 23, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,57 @@ 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} />; } } }