Created
June 20, 2017 23:38
-
-
Save dralletje/88645dd7354c85e0ce2cfc8240c045d3 to your computer and use it in GitHub Desktop.
The all new Redux React
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 'react-redux'; | |
| export class Lifecycle extends React.Component { | |
| props: { | |
| componentDidMount?: () => mixed, | |
| }; | |
| componentDidMount() { | |
| if (this.props.componentDidMount) { | |
| this.props.componentDidMount(); | |
| } | |
| } | |
| render() { | |
| return this.children || null; | |
| } | |
| } | |
| // Really struggling what to name this. | |
| // So far I thouhgt Null, Empty, Void, SideEffect, Effect... idk, | |
| // really don't want to use "xxxComponent", that would make it too long. | |
| // TODO Optimally would be "inlined" (idk?!) by a babel plugin | |
| export class Void extends React.Component { | |
| render() { | |
| return null; | |
| } | |
| } | |
| // Method works "inside" of connect, but does take all it's config | |
| // from the props. This pattern can be used on other hoc-s as well, | |
| // allowing them to be used "dynamically" as func-as-child components. | |
| export const Action = connect(null, (dispatch, props) => { | |
| // The null as first argument means "need no state from redux", | |
| // but we do want to use something in mapPropsToDispatch | |
| return { | |
| action: (...args) => { | |
| return dispatch(props.action(...args)); | |
| }, | |
| }; | |
| })(props => (props.children ? props.children(props.action) : <Void />)); | |
| // Now we combine the two to make a component that runs a action | |
| // when it is rendered. | |
| export const InitialAction = ({ action }) => { | |
| return ( | |
| <Action action={action}> | |
| {action => | |
| <Lifecycle | |
| componentDidMount={() => { | |
| action(); | |
| }} | |
| />} | |
| </Action> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment