Created
January 29, 2015 01:01
-
-
Save AndrewIngram/1dd3dfb8e754080dad6c to your computer and use it in GitHub Desktop.
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 shallowEqual from 'react/lib/shallowEqual'; | |
class PureRenderComponent extends React.Component { | |
shouldComponentUpdate(nextProps, nextState) { | |
return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); | |
} | |
} | |
class FluxComponent extends PureRenderComponent { | |
constructor(props) { | |
super(props); | |
this.state = this.getStateFromFlux(); | |
} | |
componentWillMount() { | |
if (!this.props.flux && (!this.context || !this.context.flux)) { | |
var namePart = this.constructor.displayName ? " of " + this.constructor.displayName : ""; | |
throw new Error("Could not find flux on this.props or this.context" + namePart); | |
} | |
} | |
componentDidMount() { | |
var flux = this.flu | |
this.storeNames.forEach(function(store) { | |
this.flux.store(store).on("change", this._setStateFromFlux); | |
}.bind(this)); | |
} | |
componentWillUnmount() { | |
this.storeNames.forEach(function(store) { | |
this.flux.store(store).removeListener("change", this._setStateFromFlux); | |
}.bind(this)); | |
} | |
_setStateFromFlux() { | |
if (this.isMounted()) { | |
this.setState(this.getStateFromFlux()); | |
} | |
} | |
getStateFromFlux() { | |
if (this.storeNames.length) { | |
throw new Error("getStateFromFlux() not defined on " this.constructor.displayName); | |
} else { | |
return {}; | |
} | |
} | |
get storeNames() { | |
return []; | |
} | |
get childContextTypes() { | |
return { | |
flux: React.PropTypes.object | |
}; | |
} | |
get contextTypes() { | |
return { | |
flux: React.PropTypes.object | |
}; | |
} | |
get flux() { | |
return this.props.flux || (this.context && this.context.flux); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment