-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrouteNode.js
70 lines (56 loc) · 2.03 KB
/
routeNode.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
import {Component, createElement} from 'react';
import PropTypes from 'prop-types';
import {getDisplayName, ifNot} from './utils';
import {autorun, toJS} from 'mobx';
import {inject} from 'mobx-react';
function routeNode(nodeName, storeName = 'routerStore') { // route node Name, routerStore name
return function routeNodeWrapper(RouteComponent) { // component Name
@inject(storeName)
class RouteNode extends Component {
constructor(props) {
super(props);
this.nodeName = nodeName;
this.routerStore = props[storeName];
ifNot(
this.routerStore,
'[react-mobx-router5][routeNode] missing routerStore'
);
this.router = this.routerStore.router || null;
ifNot(
this.router && this.router.hasPlugin('MOBX_PLUGIN'),
'[react-mobx-router5][routeNode] missing mobx plugin'
);
this.state = {
route: this.routerStore.route
};
this.shouldUpdateNode = this.routerStore.shouldUpdateNodeFactory(this.nodeName);
}
componentDidMount() {
this.autorunDisposer = autorun(() => {
// Change state only if this should update
// This will re-render this component and so the wrapped RouteSegment component
if (this.shouldUpdateNode.get()) {
this.setState({
route: this.routerStore.route
});
}
});
}
componentWillUnmount() {
this.autorunDisposer();
}
render() {
const {route} = this.state;
const plainRoute = toJS(route); // convert to plain object
return createElement(RouteComponent, {...this.props, [storeName]: this.props[storeName], route, plainRoute});
}
}
RouteNode.displayName = 'RouteNode[' + getDisplayName(RouteComponent) + ']';
// Because @inject creates an extra HOC
RouteNode.wrappedComponent.propTypes /* remove-proptypes */ = {
[storeName]: PropTypes.object.isRequired
};
return RouteNode;
};
}
export default routeNode;