-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnect.tsx
390 lines (343 loc) · 12.9 KB
/
connect.tsx
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
const store: { [namespace: string]: any } = {};
const models: { [namespace: string]: Model } = {};
const dispatchs: { [uniqueId: string]: any } = {};
const stateToProps: { [uniqueId: string]: any } = {};
const suspendedGenerators: { [namespace: string]: { [actionType: string]: Generator } } = {};
const takeGeneratorsBinders: { [namespace: string]: { [actionType: string]: Function } } = {};
interface Async {
put: typeof connect.dispatch;
call: typeof async.call;
select: typeof async.select;
all: typeof async.all;
take: typeof async.take;
}
export interface Model {
namespace: string;
state: any;
reducers: {
[props: string]: (state: { [key: string]: any }, dispatchState: { [key: string]: any }) => object;
};
effects?: {
[props: string]: [(dispatchState: any, async: Async) => any, TakeType] | ((dispatchState: any, async: Async) => any);
};
}
export type TakeType = { type: 'takeLatest' | 'takeEvery' };
export type MapStateToProps = (_store: any) => any;
export type Action = { type: string; [props: string]: any };
export type UseConnectType = [any, (action: Action) => void];
export interface ConnectConfigProps {
withRef: boolean;
}
const reducer: React.Reducer<any, Action> = () => {
return { ...store };
};
function generateId(): string {
return Math.random().toString(16) + (+new Date()).toString(16);
}
function dispatchStore(namespaces: string[], dispatchId: React.MutableRefObject<string>, dispatch: Function, mapStateToProps: Function) {
if (!dispatchId.current) {
dispatchId.current = generateId();
namespaces.forEach((namespace: string) => {
!dispatchs[namespace] && ((dispatchs[namespace] = {}), (stateToProps[namespace] = {}));
dispatchs[namespace][dispatchId.current] = dispatch;
stateToProps[namespace][dispatchId.current] = mapStateToProps;
});
}
}
function dispatchEffect() {
return () => {
this.namespaces.forEach((namespace: string) => {
dispatchs[namespace][this.dispatchId] = null;
delete dispatchs[namespace][this.dispatchId];
if (!Object.getOwnPropertyNames(dispatchs[namespace]).length) {
delete dispatchs[namespace];
}
});
};
}
/**
* 将当前组件与全局store关联 --Hook用法
* @param {MapStateToProps} mapStateToProps 状态到属性props,传递给组件
* @param {string[]} namespaces 模型命名空间字符串组成的数组
* @returns {JSX.Element}
*/
function useConnect(mapStateToProps: MapStateToProps, namespaces: string[]): UseConnectType {
const [state, dispatch] = React.useReducer(reducer, store);
const dispatchId = React.useRef('');
dispatchStore(namespaces, dispatchId, dispatch, mapStateToProps);
React.useEffect(dispatchEffect.bind({ namespaces, dispatchId: dispatchId.current }), []);
const mapState = mapStateToProps(state);
return [mapState, connect.dispatch];
}
/**
* 将当前组件与全局store关联--Class组件用法(同时支持函数组件)
* @param {MapStateToProps} mapStateToProps 状态到属性props,传递给组件
* @param {string[]} namespaces 模型命名空间字符串组成的数组
* @param {connectConfigProps} config 可设置是否获取组件的ref
* @returns {JSX.Element}
*/
function connect(mapStateToProps: MapStateToProps, namespaces: string[], config?: ConnectConfigProps) {
return function (Component: React.ElementType) {
if (!namespaces) {
console.error('请传入与该组件相关的namespaces');
return null;
}
const withRef = config && config.withRef;
function ConnectComponent(props: any = {}, ref: React.Ref<any>): JSX.Element {
if (!store[namespaces[0]]) {
const getDerivedStateFromProps = (Component as any).getDerivedStateFromProps;
getDerivedStateFromProps && getDerivedStateFromProps();
}
const dispatchId = React.useRef('');
const [state, dispatch] = React.useReducer(reducer, store);
dispatchStore(namespaces, dispatchId, dispatch, mapStateToProps);
React.useEffect(dispatchEffect.bind({ namespaces, dispatchId: dispatchId.current }), []);
const mapState = mapStateToProps(store);
const componentProps = { ...mapState, ...props };
return React.useMemo(
() => {
if (withRef) {
return <Component ref={ref} dispatch={connect.dispatch} {...componentProps} />;
}
return <Component dispatch={connect.dispatch} {...componentProps} />;
},
Object.keys(componentProps).map((prop) => (componentProps[prop] === undefined ? prop : componentProps[prop]))
);
}
if (withRef) {
return React.forwardRef(ConnectComponent);
}
return ConnectComponent;
};
}
/**
* 装载model
* @param model 模型对象
*/
connect.model = function (model: Model) {
if (models[model.namespace]) {
return;
}
//初始化model数据
store[model.namespace] = model.state || {};
//初始化model
models[model.namespace] = model;
};
/**
* 卸载model
* @param model 模型对象
*/
connect.unmodel = function (namespace: string) {
//卸载model相关数据
store[namespace] = null;
delete store[namespace];
//卸载model
models[namespace] = null;
delete models[namespace];
//卸载相关的异步流缓存
suspendedGenerators[namespace] = null;
delete suspendedGenerators[namespace];
takeGeneratorsBinders[namespace] = null;
delete takeGeneratorsBinders[namespace];
};
/**
* 获取所有model
* @returns
*/
connect.models = models;
/**获取全局单例状态副本*/
connect.getState = function (namespace?: string) {
if (namespace) {
return store[namespace];
}
return { ...store };
};
/**发起action*/
connect.dispatch = function (action: Action) {
const { type, ...state } = action;
const [namespace, key] = type.split('/');
if (!models[namespace]) {
console.warn('未加载该命名空间的model,发起更新失败,请检查type', type);
return;
}
//执行监听中的takeAction,执行完后删除
const takeGeneratorsBinder = takeGeneratorsBinders[namespace]?.[type];
if (takeGeneratorsBinder) {
takeGeneratorsBinder(state);
takeGeneratorsBinders[namespace][type] = null;
delete takeGeneratorsBinders[namespace][type];
}
const effect = models[namespace]?.effects?.[key];
if (effect) {
let takeType: TakeType;
let effectFunc = effect as Function;
if (effect instanceof Array) {
effectFunc = effect[0];
takeType = effect[1];
}
const suspendedGenerator: Generator = suspendedGenerators[namespace]?.[type];
//如果之前已经存在该type的suspendedGenerator,则直接停止执行并丢弃,继续执行新的Generator
if (suspendedGenerator && takeType && takeType.type === 'takeLatest') {
suspendedGenerator.return('canceled');
suspendedGenerators[namespace][type] = null;
delete suspendedGenerators[namespace][type];
}
const generator = effectFunc(action, {
...async,
put: async.put(namespace),
take: async.take.bind({ namespace })
});
return new Promise((res, rej) => {
if (generator?.next) {
//存储当前的Generator
if (takeType && takeType.type === 'takeLatest') {
suspendedGenerators[namespace] = suspendedGenerators[namespace] || {};
suspendedGenerators[namespace][type] = generator;
}
GeneratorExec.bind({ generator, finished: res })();
return;
}
res(generator);
});
}
const reducer = models[namespace]?.reducers?.[key];
if (!reducer || typeof reducer !== 'function') {
return;
}
const oldState = store[namespace];
const reducerState = reducer(oldState, state) as any;
//如果状态没有变化,则直接返回,不触发更新
let update = true;
try {
if (JSON.stringify(reducerState) === JSON.stringify(oldState)) {
update = false;
for (let key in reducerState) {
if (!Object.is(reducerState[key], oldState[key])) {
update = true;
break;
}
}
}
} catch (err) {}
if (!update) {
return;
}
//更新全局状态
store[namespace] = reducerState;
//限制在当前namesapce命名空间下进行dispatch,避免执行很多不必要的程序
for (const dispatchId in dispatchs[namespace]) {
try {
const mapStateToPropsFunc = stateToProps[namespace][dispatchId];
const finalProps = mapStateToPropsFunc(store);
const oldProps = mapStateToPropsFunc({ ...store, [namespace]: oldState });
//根据mapStateToProps结果,判定是否需要更新
if (JSON.stringify(finalProps) !== JSON.stringify(oldProps)) {
dispatchs[namespace][dispatchId]({ type, reducerState });
}
} catch (err) {
console.error('mapStateToProps比对失败,继续执行dispatch', err);
dispatchs[namespace][dispatchId]({ type, reducerState });
}
}
};
//处理generator
function GeneratorExec(promiseValue?: any, manualValue?: any) {
var GeneratorExecBinder = GeneratorExec.bind(this);
const { value, done } = manualValue || this.generator.next(promiseValue);
if (promiseValue instanceof Function) {
promiseValue();
}
if (done) {
this.finished(value);
return;
}
if (value instanceof Promise) {
value.then(GeneratorExecBinder).catch((error) => {
GeneratorExecBinder(undefined, this.generator.throw(new Error(error)));
//临时保留不拋异常,继续往下执行的逻辑-勿删
// GeneratorExecBinder({ error, data: { success: false } });
});
return;
}
if (value instanceof AsyncType) {
//如果是take,暂存并监听该action
if (value.type === 'take') {
const namespace = value.value.split('/')[0];
takeGeneratorsBinders[namespace] = takeGeneratorsBinders[namespace] || {};
takeGeneratorsBinders[namespace][value.value] = GeneratorExecBinder;
return;
}
if (value.type === 'put') {
const [namespace, key] = value.value.type.split('/');
if (models[namespace]?.effects?.[key]) {
const manualValue = this.generator.next();
connect.dispatch(value.value);
GeneratorExecBinder(null, manualValue);
return;
}
connect.dispatch(value.value);
}
if (value.type === 'put.resolve') {
const dispatchResult = connect.dispatch(value.value);
if (dispatchResult instanceof Promise) {
dispatchResult.then(GeneratorExecBinder);
return;
}
GeneratorExecBinder(dispatchResult);
return;
}
}
GeneratorExecBinder(value);
}
/**异步类型*/
class AsyncType {
/**
* @param type 异步类型
* @param value 异步传参值
*/
constructor(public type: string, public value?: any) {
this.type = type;
this.value = value;
}
}
/**模拟saga 函数 */
const async = {
put: function (namespace: string) {
function put(action: Action) {
if (!action.type.includes('/')) {
action.type = namespace + '/' + action.type;
}
return new (AsyncType as any)('put', action);
}
put.resolve = function (action: Action) {
if (!action.type.includes('/')) {
action.type = namespace + '/' + action.type;
}
return new (AsyncType as any)('put.resolve', action);
};
return put;
},
call: function (callFunc: Function, ...args: any[]) {
return callFunc(...args);
},
select: function (selectFunc?: (clone_store: typeof store) => any) {
return selectFunc ? selectFunc({ ...store }) : { ...store };
},
all: function (promiseArray: (Promise<any> | AsyncType)[]): Promise<any> {
return Promise.all(
promiseArray.map((item: any) => {
if (item instanceof AsyncType) {
return connect.dispatch(item.value);
}
return item;
})
);
},
take: function (actionKey: string) {
if (!actionKey.includes('/')) {
actionKey = this.namespace + '/' + actionKey;
}
return new (AsyncType as any)('take', actionKey);
}
};
export { useConnect, connect };