Skip to content

Commit 65d20b2

Browse files
committed
feat: add mapping state service
1 parent 554de43 commit 65d20b2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/services/stateService.tsx

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import * as React from 'react';
2+
import { EventService } from 'mo/services/eventService';
3+
import { cloneInstance } from 'mo/common/utils';
4+
import Logger from 'mo/common/logger';
5+
6+
/**
7+
* Mapping the state to the component
8+
* @param WrappedComponent The component will be wrapped
9+
* @param state The state you want to injected
10+
* @param subscribes The events of your subscribe, it used to trigger the state re render
11+
*/
12+
export function mapState<S>(WrappedComponent: React.ComponentType<any>, state: S, events: string | string []) {
13+
return class StateProvider extends React.Component {
14+
state: S;
15+
constructor(props) {
16+
super(props);
17+
this.onChange = this.onChange.bind(this);
18+
this.state = cloneInstance(state);
19+
}
20+
21+
componentDidMount() {
22+
EventService.subscribe(events, this.onChange);
23+
}
24+
25+
onChange() {
26+
const nextState = cloneInstance(state);
27+
Logger.info(nextState);
28+
this.setState(nextState);
29+
}
30+
31+
render() {
32+
return (
33+
<WrappedComponent {...this.state} {...this.props} />
34+
);
35+
}
36+
};
37+
}

0 commit comments

Comments
 (0)