54 lines
1.2 KiB
JavaScript
54 lines
1.2 KiB
JavaScript
import React from 'react';
|
|
|
|
import Store from './Store.js';
|
|
|
|
// "react-redux connect()"-like example
|
|
class StoreListener extends React.PureComponent
|
|
{
|
|
componentDidMount()
|
|
{
|
|
Store.on(this.update);
|
|
}
|
|
|
|
componentWillUnmount()
|
|
{
|
|
Store.un(this.update);
|
|
}
|
|
|
|
update = () =>
|
|
{
|
|
var newState = this.mapStateToProps(Store.data);
|
|
for (var i in newState)
|
|
{
|
|
if (this.state[i] != newState[i])
|
|
{
|
|
this.setState(newState);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
render()
|
|
{
|
|
var props = { ...this.initial, ...this.props, ...this.state };
|
|
return React.createElement(this.wrappedComponent, props);
|
|
}
|
|
}
|
|
|
|
export default function(component, map, initial)
|
|
{
|
|
var cl = class extends StoreListener
|
|
{
|
|
constructor(props, context, updater)
|
|
{
|
|
super(props, context, updater);
|
|
this.wrappedComponent = component;
|
|
this.mapStateToProps = map;
|
|
this.initial = initial;
|
|
this.state = map(Store.data);
|
|
this.update = this.update.bind(this);
|
|
}
|
|
};
|
|
return cl;
|
|
};
|