Last active
April 11, 2017 20:27
-
-
Save viankakrisna/031b7dc3fab1148fb591f0717cbe47dd to your computer and use it in GitHub Desktop.
re-implementation of redux and react-redux by 52 LOC https://www.webpackbin.com/bins/-KhSxnW73-R4iCMwdfnW
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"; | |
let store; | |
export default function createStore( | |
reducer, | |
initialState = {}, | |
...middlewares | |
) { | |
const subscribers = []; | |
let newState = initialState; | |
store = { | |
dispatch: action => { | |
newState = reducer(initialState, action); | |
subscribers.forEach(f => f(newState, store.dispatch)); | |
}, | |
getState: () => newState, | |
subscribe: cb => { | |
subscribers.push(cb); | |
return () => subscribers.splice(subscribers.indexOf(cb), 1); | |
} | |
}; | |
return store; | |
} | |
const getStore = () => store; | |
export const connect = (mapStateToProps = e => null, mapDispatchToProps) => | |
Component => | |
class ConnectedComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.store = getStore(); | |
this.state = mapStateToProps(this.store.getState()) | |
this.unsubscribe = this.store.subscribe(()=>{ | |
this.setState(mapStateToProps(this.store.getState())) | |
}); | |
} | |
componentWillUnmount(){ | |
this.unsubscribe() | |
} | |
render() { | |
return ( | |
<Component | |
{...this.props} | |
{...this.state} | |
{...mapDispatchToProps | |
? mapDispatchToProps(this.store.dispatch) | |
: { dispatch: this.store.dispatch }} | |
/> | |
); | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment