-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiracleHooks.js
82 lines (73 loc) · 1.77 KB
/
MiracleHooks.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
82
import {useState, useEffect} from 'react';
import {
subscribe,
SubscribeMatchType,
setInitialState,
getStore
} from './MiracleObserver.js';
export function useMiracleStore(initialFunc, updateFunc) {
const [value, setValue] = useState(setInitialState(initialFunc));
const initValue = () => {
setValue(setInitialState(initialFunc));
};
const updateValue = (_value, store) => {
if (store) {
setValue(updateFunc(_value, store));
} else {
setValue(updateFunc(_value, getStore()));
}
};
return [value, updateValue, initValue];
}
/**
*
* @param key
* @param cbGetState // 注意:回调中值状态的引用不再变化
* @param matchType
* @param period
* @param throttle
* @param preprocessing
* @returns {*[]}
*/
export function useMiracleObserver(
key,
cbGetState,
matchType = SubscribeMatchType.ExactMatch,
period = 0,
throttle = 0,
preprocessing = null,
) {
const [staticTag] = useState(key);
useEffect(() => {
// console.debug('create subscribe in useEffect', key);
const sub = subscribe(
key,
cbGetState,
matchType,
period,
throttle,
preprocessing,
);
return () => {
// console.debug('unsubscribe in useEffect', key);
sub.unsubscribe();
};
}, [staticTag]);
return [];
}
export function useMiracleObserverHot(
key,
cbGetState,
matchType = SubscribeMatchType.ExactMatch,
preprocessing = null,
) {
useEffect(() => {
// console.debug('create subscribe in useEffect: hot ', key);
const sub = subscribe(key, cbGetState, matchType, 0, 0, preprocessing);
return () => {
// console.debug('unsubscribe in useEffect: hot ', key);
sub.unsubscribe();
};
}, [cbGetState, key, matchType, preprocessing]);
return [];
}