-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect.js
56 lines (44 loc) · 1.36 KB
/
connect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import React from 'react';
import bindActionCreators from './bindActionCreators';
const noop = () => ({});
export default function connect(mapStateToProps, mapDispatchToProps) {
mapStateToProps = mapStateToProps || noop;
mapDispatchToProps = mapDispatchToProps || noop;
return function (Component) {
return class ConnectedComponent extends React.Component {
constructor(props, context) {
super(props, context);
if (typeof mapDispatchToProps === 'object') {
mapDispatchToProps = () => bindActionCreators(
mapDispatchToProps,
this.context.store.dispatch
);
}
this.state = this.getStateFromStore()
}
static contextTypes = {
store: React.PropTypes.object.isRequired
}
getStateFromStore() {
return Object.assign(
{},
mapStateToProps(this.context.store.getState(), this.props),
mapDispatchToProps(this.context.store.dispatch, this.props),
this.props
)
}
componentDidMount() {
this.context.store.subscribe(this._onChange.bind(this));
}
_onChange() {
const newState = this.getStateFromStore();
if (this.state !== newState) {
this.setState(newState);
}
}
render() {
return <Component {...this.state} />
}
}
}
}