Skip to content

Instantly share code, notes, and snippets.

@shokai
Last active April 22, 2016 08:30
Show Gist options
  • Select an option

  • Save shokai/dee7a556ecbcea5c8cc9acfbe8be6d83 to your computer and use it in GitHub Desktop.

Select an option

Save shokai/dee7a556ecbcea5c8cc9acfbe8be6d83 to your computer and use it in GitHub Desktop.
subscribe redux store without react-redux
export class Component extends React.Component{
mapState(state){
return state;
}
shouldComponentUpdate(nextProps, nextState){
if(Object.keys(nextState).length !== Object.keys(this.state).length ||
Object.keys(nextProps).length !== Object.keys(this.props).length){
return true;
}
for(let k in nextState){
if(typeof nextState[k] === "object" ||
this.state[k] !== nextState[k]) return true;
}
for(let k in nextProps){
if(typeof nextProps[k] === "object" ||
this.props[k] !== nextProps[k]) return true;
}
return false;
}
componentWillUnmount(){
this.unsubscribeStore();
}
componentDidMount(){
this.unsubscribeStore = store.subscribe(() => {
this.setState(this.mapState(store.getState()));
});
}
constructor(){
super();
this.state = this.mapState(store.getState());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment