Created
May 15, 2020 15:01
-
-
Save georg3103/cf6e7e2ca58f7a1a1f461f702c11342c 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
const Context = React.createContext() | |
function connect (mapStateToProps) { | |
return (Component) => { | |
class Receiver extends React.Component { | |
componentDidMount() { | |
const { subscribe } = this.props.store | |
this.unsubcribe = subscribe(() => this.forceUpdate()) | |
} | |
componentWillUnmount() { | |
this.unsubcribe() | |
} | |
render() { | |
const { dispatch, getState } = this.props.store | |
const state = getState() | |
const stateNeeded = mapStateToProps(state) | |
return <Component {...stateNeeded} dispatch={dispatch} /> | |
} | |
} | |
class ConnectedComponent extends React.Component { | |
render() { | |
return ( | |
<Context.Consumer> | |
{(store) => <Receiver store={store}/>} | |
</Context.Consumer> | |
) | |
} | |
} | |
return ConnectedComponent | |
} | |
} | |
class Provider extends React.Component { | |
render() { | |
return ( | |
<Context.Provider value={this.props.store}> | |
{this.props.children} | |
</Context.Provider> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment