Last active
August 29, 2015 14:23
-
-
Save mmerickel/7ff08ab9ee96740dedd4 to your computer and use it in GitHub Desktop.
redux bindActions decorator
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'; | |
import {connect} from 'redux/react'; | |
import {bindActions} from './utils/bindActions'; | |
import * as Actions from './actions'; | |
@connect(state => ({ | |
activePage: state.activePage, | |
})) | |
@bindActions({ | |
gotoPage: Actions.gotoPage, | |
}) | |
class MyApp extends React.Component { | |
render() { | |
return ( | |
<button onClick={this.props.gotoPage}>Switch Page</button> | |
); | |
} | |
} |
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'; | |
import shallowEqualScalar from 'redux/lib/utils/shallowEqualScalar'; | |
import {bindActionCreators} from 'redux'; | |
export function bindActions(actionMap) { | |
return DecoratedComponent => class BindDecorator extends React.Component { | |
static DecoratedComponent = DecoratedComponent; | |
shouldComponentUpdate(nextProps) { | |
return !shallowEqualScalar(this.props, nextProps); | |
} | |
render() { | |
return ( | |
<BindComponent actions={actionMap}> | |
{actions => <DecoratedComponent {...actions} {...this.props} />} | |
</BindComponent> | |
); | |
} | |
}; | |
} | |
export class BindComponent extends React.Component { | |
static contextTypes = { | |
redux: React.PropTypes.object.isRequired, | |
} | |
static propTypes = { | |
actions: React.PropTypes.object.isRequired, | |
children: React.PropTypes.func.isRequired, | |
} | |
static defaultProps = { | |
actions: {}, | |
} | |
constructor(props, context) { | |
super(props, context); | |
this.state = { | |
actions: this.actionState(props, context), | |
}; | |
} | |
componentWillReceiveProps(nextProps) { | |
if (nextProps.actions !== this.props.actions) { | |
this.handleChange(nextProps); | |
} | |
} | |
shouldComponentUpdate(nextProps) { | |
return !shallowEqualScalar(this.props, nextProps); | |
} | |
actionState(props, context) { | |
const {redux: {dispatch}} = context; | |
return bindActionCreators(props.actions, dispatch); | |
} | |
handleChange(props) { | |
this.setState({ | |
actions: this.actionState(props, this.context), | |
}); | |
} | |
render() { | |
const {children} = this.props; | |
const {actions} = this.state; | |
return children(actions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment