-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInjector.js
81 lines (65 loc) · 2.54 KB
/
Injector.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import hoistNonReactStatics from 'hoist-non-react-statics';
import invariant from 'invariant';
export default function ({ reducers, sagas }) {
let injected = false;
return function injector(WrappedComponent) {
class Injector extends Component {
static propTypes = {
forwardRef: PropTypes.object,
};
static defaultProps = {
forwardRef: undefined,
};
static contextTypes = {
store: PropTypes.shape({
injectReducers: PropTypes.func,
injectSagas: PropTypes.func,
}),
};
/**
* Inject the reducers and sagas on mount
*/
componentWillMount() {
if (injected === true) {
return;
}
if (reducers && Object.keys(reducers).length > 0) {
invariant(
this.context.store && this.context.store.injectReducers,
'No store or no injectReducers function on store. Make sure the store is enhanced with the injector enhancer',
);
this.context.store.injectReducers(reducers);
}
if (sagas && (typeof sagas === 'function' || sagas.length > 0)) {
invariant(
this.context.store && this.context.store.injectSagas,
'No store or no injectSagas function on store. Make sure the store is enhanced with the injector enhancer',
);
this.context.store.injectSagas(sagas);
}
injected = true;
}
render() {
if (this.props.forwardRef) {
return React.createElement(WrappedComponent, {
ref: this.props.forwardRef,
});
}
return React.createElement(WrappedComponent);
}
}
hoistNonReactStatics(Injector, WrappedComponent);
function forwardRef(props, ref) {
return (
<Injector
{ ...props }
forwardRef={ ref }
/>
)
}
forwardRef.displayName = `Injector-${ WrappedComponent.displayName || WrappedComponent.name || 'Component' }`;
return React.forwardRef(forwardRef);
};
}