Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Created January 29, 2015 01:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewIngram/1dd3dfb8e754080dad6c to your computer and use it in GitHub Desktop.
Save AndrewIngram/1dd3dfb8e754080dad6c to your computer and use it in GitHub Desktop.
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